Introduction
Here, we’ll understand how we can create a RESTful API in .NET Core using Entity Framework Core and PostgreSQL as the database. We’ll create a simple API for managing a list of books.
Step 1: Create a New .NET Core Web API Project
Create a new .NET Core Web API project using the following command:
dotnet new webapi -n BookstoreApi
Step 2: Install Required Packages
In your project, install the necessary NuGet packages for Entity Framework Core and PostgreSQL:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
Step 3: Define Model and DbContext
Create a model class for your books and a DbContext
to interact with the database.
// Book.cs
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
}
// ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Book> Books { get; set; }
}
Step 4: Configure Connection String
In the appsettings.json
file, configure your PostgreSQL connection string:
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=BookstoreDb;Username=myuser;Password=mypassword"
}
Step 5: Configure Services
In the Startup.cs
file, configure the services and database context:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
// ...
}
Step 6: Create Controllers
Generate a controller for the Book
model using the following command:
dotnet aspnet-codegenerator controller -name BooksController -async -api -m Book -dc ApplicationDbContext
Step 7: Run Migrations
Create the database and apply migrations:
dotnet ef migrations add InitialCreate
dotnet ef database update
Step 8: Implement the API
In the generated BooksController.cs
file, implement the API actions:
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
private readonly ApplicationDbContext _context;
public BooksController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Book>>> GetBooks()
{
return await _context.Books.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Book>> GetBook(int id)
{
var book = await _context.Books.FindAsync(id);
if (book == null)
{
return NotFound();
}
return book;
}
[HttpPost]
public async Task<ActionResult<Book>> CreateBook(Book book)
{
_context.Books.Add(book);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetBook), new { id = book.Id }, book);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateBook(int id, Book book)
{
if (id != book.Id)
{
return BadRequest();
}
_context.Entry(book).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BookExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteBook(int id)
{
var book = await _context.Books.FindAsync(id);
if (book == null)
{
return NotFound();
}
_context.Books.Remove(book);
await _context.SaveChangesAsync();
return NoContent();
}
private bool BookExists(int id)
{
return _context.Books.Any(e => e.Id == id);
}
}
Step 9: Test the API
Run your ASP.NET Core API using the command dotnet run
. You can use tools like Postman to test the API endpoints (GET
, POST
, PUT
, DELETE
) for managing books.
This example demonstrates how to create a RESTful API in .NET Core using Entity Framework Core and PostgreSQL. You can build upon this foundation to add more features, validation, authentication, and other functionality based on your application’s requirements.