Connect database to ASP.NET Core Web API

Part 1: Configuring database context with EF Core for REST API

Basic REST API from template

dotnet new webapi   (dotnet restore is done by default)
dotnet run
Program.cs → Includes main function of application
Startup.cs → Configure application with middleware
app.csproj → Contains dependency of application
Controllers/WeatherForcastController.cs → GET endpoint
WeatherForcast.cs → Data model for weather
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.InMemory

Add data model

Models/User.cs

Add database context

Models/UserDbContext.cs

Configure database context

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserDbContext>(opts =>
opts.UseInMemoryDatabase("userDB"));
services.AddScoped<UserDbContext>();
services.AddControllers();
}

Add controller and inject database context

Controllers/UserController.cs
[ {"userId":100,"firstName":"Tom","dateOfBirth":"2019-10-29"},        
{"userId":200,"firstName":"Arthur","dateOfBirth":"2019-10-29"} ]

Add another database context

- Models/Book.cs - 
public class Book {
public long BookId { get; set; }
public string BookName { get; set; }
}
- Models/User.cs -
public class User {
public long UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
Models/DatabaseContext.cs
- Startup.cs -
services.AddDbContext<DatabaseContext>(opts =>
opts.UseInMemoryDatabase("database"));
services.AddSingleton<DatabaseContext>();
Controllers/ApiController.cs
// POST request to create User
curl -k --request POST https://localhost:5001/api/user \
--header "Content-Type: application/json" \
--data '{"userId":100, "FirstName":"Tom","LastName":"Shelby"}'
// GET request to fetch users
curl -k https://localhost:5001/api/users
// POST request to create Book
curl -k --request POST https://localhost:5001/api/book \
--header "Content-Type: application/json" \
--data '{"BookId":200,"BookName":"xyz"}'
// GET request to fetch users
curl -k https://localhost:5001/api/books
git clone https://github.com/udarabibile/aspnetcore-webapi.git
cd aspnetcore-webapi
git checkout configure-dbcontext
dotnet restore
dotnet run
curl GET and POST requests

Full Stack Developer | BiBi

Get the Medium app