Connect database to ASP.NET Core Web API

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

Udara Bibile

--

.NET Core and ASP.NET Core are Microsoft’s approach to make Windows only .NET Framework to function cross-platform such as Linux, Mac OS. Preferred language used with .NET eco-system is C#.

Basic REST API from template

As prerequisites for following code .NET Core 3.0 SDK is to be installed and it can be verified in terminal as dotnet --version. In order to create a new project type in dotnet new, and options are listed to scaffolding range of applications. REST API development can be started with ASP.NET Core 3.0 Web API template.

dotnet new webapi   (dotnet restore is done by default)
dotnet run

Navigate to https://localhost:5001/weatherforecast and check GET response from Web API. Let's dig into basic project structure of template application.

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

If we look into controller code it could be seen that GET endpoint just generates hard-coded models there are returns. No persistent interaction with database is happening here. (WeatherForcast related controller and model can be removed as new endpoints will be introduced.)

Here Entity Framework Core or simply EF Core 3.0 will be used as ORM for connecting to databases, and EF Core InMemory database used for this tutorial. (Note: this is advised to be used only in testing scope.) Let’s install required NuGet packages for this application.

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.InMemory

Add data model

Add User class to be added as database model into folder called Models.

--

--