Sunday, August 18, 2024

C#.NET Core 8.0 - Entity Framework Code First Approach with API Layer

In this guide, we'll walk through setting up a basic .NET Core 8.0 application using the Entity Framework Code First approach, combined with an API layer. This approach allows you to define your database schema directly in your C# code, making it easy to manage changes over time.

1. Setup the .NET Core Project

Start by creating a new .NET Core Web API project:

dotnet new webapi -n EFCoreApiExample

cd EFCoreApiExample

2. Install Required Packages

Add Entity Framework Core and the SQL Server provider:

dotnet add package Microsoft.EntityFrameworkCore

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

dotnet add package Microsoft.EntityFrameworkCore.Tools

3. Define the Data Model

Create your entity classes. For instance, we'll create a `Product` class.

public class Product

{

    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price { get; set; }

}

4. Setup the DbContext

Create a `DbContext` class that will handle your database operations:

public class ApplicationDbContext : DbContext

{

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) {}

    public DbSet<Product> Products { get; set; }

}

5. Configure the Connection String

In `appsettings.json`, add the connection string:

"ConnectionStrings": {

  "DefaultConnection": "Server=.;Database=EFCoreApiDb;Trusted_Connection=True;"

}

Then configure the `DbContext` in `Program.cs`:

builder.Services.AddDbContext<ApplicationDbContext>(options =>

options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

6. Create the Database

Run the following commands to create a migration and update the database:

dotnet ef migrations add InitialCreate

dotnet ef database update

7. Create the API Controller

Add a new `ProductsController` to handle CRUD operations:

[Route("api/[controller]")]

[ApiController]

public class ProductsController : ControllerBase

{

    private readonly ApplicationDbContext _context;

    public ProductsController(ApplicationDbContext context)

    {

        _context = context;

    }

    [HttpGet]

    public async Task<ActionResult<IEnumerable<Product>>> GetProducts()

    {

        return await _context.Products.ToListAsync();

    }

    [HttpGet("{id}")]

    public async Task<ActionResult<Product>> GetProduct(int id)

    {

        var product = await _context.Products.FindAsync(id);


        if (product == null)

        {

            return NotFound();

        }

        return product;

    }

    [HttpPost]

    public async Task<ActionResult<Product>> PostProduct(Product product)

    {

        _context.Products.Add(product);

        await _context.SaveChangesAsync();

        return CreatedAtAction("GetProduct", new { id = product.Id }, product);

    }

    [HttpPut("{id}")]

    public async Task<IActionResult> PutProduct(int id, Product product)

    {

        if (id != product.Id)

        {

            return BadRequest();

        }

        _context.Entry(product).State = EntityState.Modified;

        try

        {

            await _context.SaveChangesAsync();

        }

        catch (DbUpdateConcurrencyException)

        {

            if (!ProductExists(id))

            {

                return NotFound();

            }

            else

            {

                throw;

            }

        }

       return NoContent();

    }

    [HttpDelete("{id}")]

    public async Task<IActionResult> DeleteProduct(int id)

    {

        var product = await _context.Products.FindAsync(id);

        if (product == null)

        {

            return NotFound();

        }

        _context.Products.Remove(product);

        await _context.SaveChangesAsync();

        return NoContent();

    }

    private bool ProductExists(int id)

    {

        return _context.Products.Any(e => e.Id == id);

    }

}

8. Run the Application

Run your application:

dotnet run

Navigate to `https://localhost:5001/api/products` to interact with the API.

Conclusion

By following this guide, you've created a .NET Core 8.0 Web API using the Entity Framework Code First approach. This setup is scalable and allows for easy database management as your application grows.