Build Minimal APIs In .NET 7 Using Entity Framework Core 7

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

Introduction

Minimal APIs are designed to create HTTP APIs with minimal dependencies. Minimal APIs are suitable for microservices and applications that include minimum files, features, and dependencies with ASP.NET Core. Minimal APIs were there since .NET 6 and it helps you to easily create API. At the time of this article write up .NET 7 is recently released.  It has included several improvements in performance, new features for C#11 &F#, .Net MAUI, ASP.NET Core/Blazor improvement, Web APIs, and many more. Additionally, you can easily containerize your .NET 7 projects as well as configure CI/CD workflows for GitHub actions. Moreover, .NET MAUI is a part of the .NET 7. .NET 7 is officially supported by Microsoft for only 18 months, and it is labeled as Standard term support. This article demonstrates how to create Minimal APIs using .NET 7 and Entity Framework Core 7.

In this article, we will cover the followings:

  • Create Minimal APIs using .NET 7
  • Get familiar with Minimal APIs
  • Get Familiar with Entity Framework and use Entity Framework in Minimal API
  • Create APIs for CRUD operation

Prerequisites

  • Visual Studio 2022
  • .NET 7 SDK

If you don’t have these prerequisites, you can download and install Visual Studio 2022 from here and .NET 7 SDK from here.

You can get the previous article Getting Started with ASP.NET Core 7 and  Some key features of.NET 7 here.

Create Minimal API Project

Follow the below steps to create a Minimal API.

Step 1 - Open Visual Studio and click on create a new project.

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

Step 2 - Select ASP.NET Core Web API as depicted below. You can see that this template comes with an example of a RESTFul HTTP service as well as it can be used for ASP.NET Core MVC Views and Controllers ( APIs with controller).

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

Step 3 - Give the project name, and directory of the project and then click on Next as illustrated below.

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

Step 4 - Select Framework:  .Net 7.0 (Standard Term Support), uncheck Use Controller to use minimal APIs. uncheck Do not use top-level Statements. Select others as illustrated in the image below.

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

Step 5 - Exploring Default Program.cs code

Now, let’s explore the code of program.cs.

Below is the default code of Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

app.Run();

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
  • The MapGet method in Minimal APIs can be used to handle the HTTP Get request. Meaning the weather forecast API is an HTTP Get endpoint: “/weatherforecast”.
  • The default Weather forecast displays the date, temperature, summary, and temperature.

Default project Structure of Minimal API project.

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

Now, let’s run the default project. Below is the view of a Swagger page.

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

You can see in the above image that Minimal API comes with a default weather forecast and Swagger Documentation for Web API same as ASP.NET Core Web API with Controller.

Up to now we have only created and explored the default Minimal API. Now, we will go for creating new APIs.

Adding/Creating New APIs

Step 1 - Add Entity Framework

Entity Framework Core: Entity Framework core is part of Entity Framework. After the Entity Framework 6.x it is labeled as Entity Framework core. Entity Framework core is an open-source, lightweight, extensible, and cross-platform version of Entity Framework. It works as an Object-relational mapper (ORM) which helps developer to work with database and .Net objects easily. With the use of EF, developers don’t need to write most of the data access code.

In Memory database: EF core has the ability to store and retrieve data from in memory. In memory database is used to test the application. It doesn’t store data in the physical database, it just stores data in the in-memory and it is volatile. We can use it just for testing whether our API is working perfectly or not in this demo Minimal API project.

So here we will install two components:

  • Microsoft.EntityFrameworkCore.InMemory
  • Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore

Now, let’s move to add EF Core.

Right-click on Project and Go to Manage NuGet Package for the solution as shown below.

Then go to the Browse tab. In the Search box enter Microsoft.EntityFrameworkCore.InMemory select Microsoft.EntityFrameworkCore.InMemory and then install it.

Similarly, Go to the Browse tab -> In the Search box enter: Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore then you select it and install it.

Step 2 - Add Model class.

Now, let’s add the Student model class. Create a Model folder and add the Student class there.

Write the below code in your Student.cs class:

public class Student
{
    public int Id { get; set; }
    [Required]
    public string? Name { get; set; }
    [Required]
    public string? Email { get; set; }
    public string? Phone { get; set; }
}

Step 3 - Add DbContext.

Then let’s create a folder Data and add a class for data context. Let’s say MyDataContext class.

Code of MyDataContext

public class MyDataContext:DbContext
{
    public MyDataContext(DbContextOptions<MyDataContext> options)
   : base(options) { }

    public DbSet<Student> Students => Set<Student>();
}

Then add Datacontext in Program.cs as shown below.

//Add dbContext, here you can we are using In-memory database.
builder.Services.AddDbContext<MyDataContext>(opt => opt.UseInMemoryDatabase("Student"));

Step 4 - Create New APIs

In Minimal API we write all the API code inside the Program.cs file. So now, let’s go and add a basic API endpoint for a CRUD operation of the Student class.

Save API: Write the below code to Save Student data using entity framework core 7 in Minimal API. Here the Save API is HTTP Post endpoint.

app.MapPost("/SaveStudent", async (Student student, MyDataContext db) =>
{
    db.Students.Add(student);
    await db.SaveChangesAsync();

    return Results.Created($"/save/{student.Id}", student);
});

GetAll: Below is the code of the GetAll Student API endpoint. This is HTTP Get API.

app.MapGet("/GetAllStudent", async (MyDataContext db) =>
    await db.Students.ToListAsync());

Update: Below is the update code for Student detail which is HTTP Put API.

app.MapPut("/UpdateStudents/{id}", async (int id, Student studentinput, MyDataContext db) =>
{
    var student = await db.Students.FindAsync(id);

    if (student is null) return Results.NotFound();

    student.Name = studentinput.Name;
    student.Phone = studentinput.Phone;

    await db.SaveChangesAsync();

    return Results.NoContent();
});

A complete code of Program.cs with Post, Get, Put, and Delete APIs for Student is given below:

using Microsoft.EntityFrameworkCore;
using SampleMinimalAPI.Data;
using SampleMinimalAPI.Model;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//Add dbContext 
builder.Services.AddDbContext<MyDataContext>(opt => opt.UseInMemoryDatabase("Student"));
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

//Student APIs
app.MapPost("/SaveStudent", async (Student student, MyDataContext db) =>
{
    db.Students.Add(student);
    await db.SaveChangesAsync();

    return Results.Created($"/save/{student.Id}", student);
});

app.MapGet("/GetAllStudent", async (MyDataContext db) =>
    await db.Students.ToListAsync());

app.MapGet("/GetStudentById/{id}", async (int id, MyDataContext db) =>
    await db.Students.FindAsync(id)
        is Student student
            ? Results.Ok(student)
            : Results.NotFound());

app.MapPut("/UpdateStudents/{id}", async (int id, Student studentinput, MyDataContext db) =>
{
    var student = await db.Students.FindAsync(id);

    if (student is null) return Results.NotFound();

    student.Name = studentinput.Name;
    student.Phone = studentinput.Phone;

    await db.SaveChangesAsync();

    return Results.NoContent();
});

app.MapDelete("/DeleteStudent/{id}", async (int id, MyDataContext db) =>
{
    if (await db.Students.FindAsync(id) is Student student)
    {
        db.Students.Remove(student);
        await db.SaveChangesAsync();
        return Results.Ok(student);
    }

    return Results.NotFound();
});

app.Run();

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

Now, our Student APIs are ready, we can run and test APIs.

Below is an image of testing for Save API.

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

Below is an image of testing for the GetAll Student API.

Build Minimal APIs in .NET 7 Using Entity Framework Core 7

In this way, we can test all the APIs of our minimal API project using an in-memory database.

The source code for Minimal APIs demonstrated in this article can be found here.

Summary

In a nutshell, Minimal APIs are designed to create HTTP APIs with minimal dependencies. Minimal APIs are suitable for microservices and applications that include minimum files, features, and dependencies with ASP.NET Core. Minimal APIs were available since .NET 6. Hence, the article described what is Minimal API and how to get started with Minimal API in .NET 7. Additionally, the article has demonstrated to create a new Custom API with an example of Student API. Furthermore, we have got an idea about Entity Framework Core 7 and implemented entity framework in the Minimal API project as well as created minimal API for CRUD operation using entity framework and in-memory database.

Reference

rijsat.com