Anto Subash.

Published on

Minimal Api with ABP - Swagger and CRUD - Part 3

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

1dotnet 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.

1dotnet add package Volo.Abp.Autofac
2dotnet add package Volo.Abp.AspNetCore.Mvc
3dotnet add package Swashbuckle.AspNetCore 
4dotnet add package Volo.Abp.EntityFrameworkCore.Sqlite
5dotnet add package Microsoft.EntityFrameworkCore.Design

Create Entity

We will create a simple Book Entity.

1public class Book : AuditedAggregateRoot<Guid>
2{
3    public Book(Guid id, string name)
4    {
5        this.Id = id;
6        this.Name = name;
7    }
8    public string Name { get; set; }
9}

Create DB Context

1public class MyDbContext : AbpDbContext<MyDbContext>
2{
3    public DbSet<Book> Books => Set<Book>();
4
5    public MyDbContext(DbContextOptions<MyDbContext> options)
6        : base(options)
7    {
8    }
9
10    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
11    {
12        base.OnConfiguring(optionsBuilder);
13        optionsBuilder.UseSqlite();
14    }
15
16    protected override void OnModelCreating(ModelBuilder builder)
17    {
18        base.OnModelCreating(builder);
19        builder.Entity<Book>(b =>
20        {
21            b.ToTable("Books");
22            b.ConfigureByConvention();
23            b.HasData(new Book(Guid.NewGuid(),"My Book"));
24        });
25    }
26}

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

Create the minimal module

1[DependsOn(
2    typeof(AbpAspNetCoreMvcModule),
3    typeof(AbpAutofacModule),
4    typeof(AbpEntityFrameworkCoreSqliteModule)
5)]
6public class MinimalModule : AbpModule
7{
8    public override void ConfigureServices(ServiceConfigurationContext context)
9    {  
10        context.Services.AddEndpointsApiExplorer();
11        context.Services.AddSwaggerGen();   
12        context.Services.AddAbpDbContext<MyDbContext>(options =>
13        {
14            options.AddDefaultRepositories(includeAllEntities: true);
15        }); 
16        Configure<AbpDbContextOptions>(options =>
17        {
18            options.UseSqlite();
19        });
20    }
21
22    public override void OnApplicationInitialization(ApplicationInitializationContext context)
23    {
24        var app = context.GetApplicationBuilder();
25        var env = context.GetEnvironment();
26        if (env.IsDevelopment())
27        {
28            app.UseSwagger();
29            app.UseSwaggerUI();
30        }
31        app.UseHttpsRedirection();
32    }
33}

Create the minimal api

1var builder = WebApplication.CreateBuilder(args);
2builder.Host.AddAppSettingsSecretsJson().UseAutofac();
3builder.Services.ReplaceConfiguration(builder.Configuration);
4builder.Services.AddApplication<MinimalModule>();
5var app = builder.Build();
6
7app.MapGet("/book", async ([FromServices] IRepository<Book, Guid> repository) =>
8{
9    return await repository.GetListAsync();
10});
11
12app.MapPost("/book", async (string name, [FromServices] IRepository<Book, Guid> repository) =>
13{
14    var newBook = await repository.InsertAsync(new Book(Guid.NewGuid(),name));
15    return Results.Created($"/book/{newBook.Id}", newBook);
16});
17
18app.MapPut("/book/{id}", async (Guid id, string name, [FromServices] IRepository<Book, Guid> repository) =>
19{
20    var book = await repository.GetAsync(id);
21    book.Name = name;
22    return await repository.UpdateAsync(book);
23});
24
25app.MapDelete("/book/{id}", async (Guid id, [FromServices] IRepository<Book, Guid> repository) =>
26{
27    var book = await repository.GetAsync(id);
28    await repository.DeleteAsync(id);
29});
30
31app.InitializeApplication();
32app.Run();

Add connection string

update the appsettings.json with the ConnectionStrings

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

Create migration

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

1dotnet ef migrations add init

Apply migrations to DB

1dotnet ef database update

Run the App

1dotnet run

View the Book

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

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