ASP.NET Web API

·

2 min read

Let’s create a web API in ASP.NET and Entity Framework to perform CRUD operation on a todolist item.

Packages

Install following packages for working with Web API:

  • Microsoft.EntityFramework

  • Microsoft.EntityFramework.Tools

  • Microsoft.EntityFramework.SqlServer (If using MySQL Database)

  • Microsoft.EntityFramework.InMemory (If using in memory database)

Model

Create the model folder and add the data model class for the item to be stored in database as:

namespace WebAPI.Models;

public class Student
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public bool IsCoder{ get; set; }
}

Database Context

On the same models folder, add database context which will act as a bridge between Entity Framework and above data model.

using Microsoft.EntityFrameworkCore;

namespace WebAPI.Models;

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

    public DbSet<Student> Student{ get; set; } = null!;
}

Add Service

The above DB Context is a service and it needs to be added in our application using dependency injection.

using Microsoft.EntityFrameworkCore;
using WebAPI.Models;
// Remaining Code...
builder.Services.AddDbContext<StudentDBContext>(opt => opt.UseInMemoryDatabase("StudentDB"));
// Remaining Code...

Controller

Add the controller for our web API and .NET provides boilerplates for easing our work. Go-to Controllers > Add > New Scaffolded Item.

Now, add the API Controller with actions, using Entity Framework.

Then, select the Model and DB Context class to reference for creating the controller.

Wallah! You now have the boilerplate generated for CRUD operation in ASP.NET!