Anto Subash.

dotnet
abp
crud

Minimal Api with ABP - Swagger and CRUD - Part 3

Table of contents

Intro

In this we will continue with the last one and create a CRUD API with Minimal API.

This is a continuation of Part 2

Create the project

dotnet new web -n MinimalAbpCRUD

Navigate to the MinimalAbpCRUD folder and add the required packages.

Add required packages

To add the required packages use the dotnet add package command.

dotnet add package Volo.Abp.Autofac
dotnet add package Volo.Abp.AspNetCore.Mvc
dotnet add package Swashbuckle.AspNetCore 
dotnet add package Volo.Abp.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design

Create Entity

We will create a simple Book Entity.

public class Book : AuditedAggregateRoot<Guid>
{
    public Book(Guid id, string name)
    {
        this.Id = id;
        this.Name = name;
    }
    public string Name { get; set; }
}

Create DB Context

public class MyDbContext : AbpDbContext<MyDbContext>
{
    public DbSet<Book> Books => Set<Book>();

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlite();
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<Book>(b =>
        {
            b.ToTable("Books");
            b.ConfigureByConvention();
            b.HasData(new Book(Guid.NewGuid(),"My Book"));
        });
    }
}

This db context will configure the entity and also seed the database with one data.

Create the minimal module

[DependsOn(
    typeof(AbpAspNetCoreMvcModule),
    typeof(AbpAutofacModule),
    typeof(AbpEntityFrameworkCoreSqliteModule)
)]
public class MinimalModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {  
        context.Services.AddEndpointsApiExplorer();
        context.Services.AddSwaggerGen();   
        context.Services.AddAbpDbContext<MyDbContext>(options =>
        {
            options.AddDefaultRepositories(includeAllEntities: true);
        }); 
        Configure<AbpDbContextOptions>(options =>
        {
            options.UseSqlite();
        });
    }

    public override void OnApplicationInitialization(ApplicationInitializationContext context)
    {
        var app = context.GetApplicationBuilder();
        var env = context.GetEnvironment();
        if (env.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }
        app.UseHttpsRedirection();
    }
}

Create the minimal api

var builder = WebApplication.CreateBuilder(args);
builder.Host.AddAppSettingsSecretsJson().UseAutofac();
builder.Services.ReplaceConfiguration(builder.Configuration);
builder.Services.AddApplication<MinimalModule>();
var app = builder.Build();

app.MapGet("/book", async ([FromServices] IRepository<Book, Guid> repository) =>
{
    return await repository.GetListAsync();
});

app.MapPost("/book", async (string name, [FromServices] IRepository<Book, Guid> repository) =>
{
    var newBook = await repository.InsertAsync(new Book(Guid.NewGuid(),name));
    return Results.Created($"/book/{newBook.Id}", newBook);
});

app.MapPut("/book/{id}", async (Guid id, string name, [FromServices] IRepository<Book, Guid> repository) =>
{
    var book = await repository.GetAsync(id);
    book.Name = name;
    return await repository.UpdateAsync(book);
});

app.MapDelete("/book/{id}", async (Guid id, [FromServices] IRepository<Book, Guid> repository) =>
{
    var book = await repository.GetAsync(id);
    await repository.DeleteAsync(id);
});

app.InitializeApplication();
app.Run();

Add connection string

update the appsettings.json with the ConnectionStrings

"ConnectionStrings": {
    "Default": "Filename=./db.sqlite"
}

Create migration

Now our app is ready lets create migrations for the DBcontext.

dotnet ef migrations add init

Apply migrations to DB

dotnet ef database update

Run the App

dotnet run

View the Book

Once the application is launched navigate to /swagger you will see swagger UI.

Repo : https://github.com/antosubash/AbpMinimalApiCRUD

Buy Me a Coffee at ko-fi.com