avatarSukhpinder Singh | .Net Developer

Summarize

Boost API Development: Mastering Minimal APIs with EF Core

Transform API Development Game and Streamline Data Management with EF Core Integration in Minimal APIs!

Photo by Douglas Lopes on Unsplash

Introduction

In the ever-evolving landscape of .NET development, the introduction of minimal APIs represents a significant shift in how developers create lightweight and efficient web applications. As a developer exploring this new paradigm, you may find yourself intrigued by its simplicity and eager to understand its potential applications. In this article, we’ll delve into the process of setting up a minimal API project and enhancing it with Entity Framework (EF) Core for data persistence.

Prerequisite

Getting Started with Minimal APIs

Before diving into the intricacies of EF Core integration, let’s first set up a minimal API project. Assuming you have the .NET 8.0 SDK installed, follow these steps:

Project Creation: Open your preferred terminal and create a new minimal API project using the .NET CLI:

dotnet new web -o PizzaStore -f net8.0

Install Swashbuckle: Swashbuckle is a useful package for generating Swagger documentation, which can aid in API development and testing. Install it using:

dotnet add package Swashbuckle.AspNetCore --version 6.5.0

Project Setup: Open the project in Visual Studio Code and create a Pizza.cs file in the project root. This file will define our data model, representing a pizza. Here's a simple example:

namespace PizzaStore.Models 
{
    public class Pizza
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Description { get; set; }
    }
}

Configuring Swagger: In the Program.cs file, configure Swagger for API documentation:

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo {
        Title = "PizzaStore API",
        Description = "Making the Pizzas you love",
        Version = "v1" });
});

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "PizzaStore API V1");
});

app.MapGet("/", () => "Hello World!");

app.Run();

Integrating EF Core for Data Persistence

With our minimal API project set up, let’s proceed to integrate Entity Framework Core for data persistence:

Install EF Core Package: Add Entity Framework Core package for in-memory database support:

dotnet add package Microsoft.EntityFrameworkCore.InMemory --version 8.0

Define DbContext: Create a PizzaDb class to serve as our DbContext and define the data storage:

using Microsoft.EntityFrameworkCore;

namespace PizzaStore.Models 
{
    class PizzaDb : DbContext
    {
        public PizzaDb(DbContextOptions options) : base(options) { }
        public DbSet<Pizza> Pizzas { get; set; } = null!;
    }
}

Register DbContext: In Program.cs, register the DbContext with dependency injection:

builder.Services.AddDbContext<PizzaDb>(options => options.UseInMemoryDatabase("items"));

Expose API Endpoints: Now, let’s expose endpoints for interacting with the pizza data. For example, to retrieve all pizzas:

app.MapGet("/pizzas", async (PizzaDb db) => await db.Pizzas.ToListAsync());

And to add a new pizza:

app.MapPost("/pizza", async (PizzaDb db, Pizza pizza) =>
{
    await db.Pizzas.AddAsync(pizza);
    await db.SaveChangesAsync();
    return Results.Created($"/pizza/{pizza.Id}", pizza);
});

Testing and Validation

Run the application and utilize Swagger UI to test the API endpoints for retrieving, adding, updating, and deleting pizzas.

Retrieve a Single Item

To retrieve a specific item by its ID, you’ll need to implement the code under the app.MapPost route that you previously set up.

Example Implementation:

app.MapGet("/pizza/{id}", async (PizzaDb db, int id) => await db.Pizzas.FindAsync(id));

Testing the GET Operation

To validate this operation, you can navigate to https://localhost:{PORT}/pizza/1 directly or utilize the Swagger UI interface. Since an in-memory database is being used, any previously created pizzas may not be listed if the application has been restarted. Thus, you may need to utilize the POST operation to add items again.

Updating an Existing Item

For updating an existing item, insert the following code under the GET /pizza/{id} route that you created earlier.

Example Implementation:

app.MapPut("/pizza/{id}", async (PizzaDb db, Pizza updatepizza, int id) =>
{
      var pizza = await db.Pizzas.FindAsync(id);
      if (pizza is null) return Results.NotFound();
      pizza.Name = updatepizza.Name;
      pizza.Description = updatepizza.Description;
      await db.SaveChangesAsync();
      return Results.NoContent();
});

Testing the PUT Operation

Navigate to PUT /pizza/{id} in the Swagger UI. Proceed to 'Try it out', enter '1' in the ID text box, and update the request body with the following JSON, modifying the name to "Pineapple":

{
   "id": 1,
   "name": "Pineapple"
}

Execute the operation. To verify the changes, revisit GET /pizza/{id}. The pizza should now reflect the name "Pineapple".

Deleting an Item

To remove an existing item, include the following code under the previously created PUT /pizza/{id} route:

Example Implementation:

app.MapDelete("/pizza/{id}", async (PizzaDb db, int id) =>
{
   var pizza = await db.Pizzas.FindAsync(id);
   if (pizza is null)
   {
      return Results.NotFound();
   }
   db.Pizzas.Remove(pizza);
   await db.SaveChangesAsync();
   return Results.Ok();
});

Testing the DELETE Operation

To verify the deletion, attempt to delete an item using the Swagger interface.

Conclusion

In this detailed walkthrough, we’ve explored the process of setting up a minimal API project and enhancing it with Entity Framework Core for data persistence. By following these steps, you’ve gained valuable insights into leveraging minimal APIs for efficient web development while integrating essential components like EF Core for robust data management.

More Articles

Follow me on

C# Publication, LinkedIn, Instagram, Twitter, Dev.to

Aspnetcore
Rest Api
Development
Dotnet
C Sharp Programming
Recommended from ReadMedium