EF Core in separate project

Whether writing stand alone application or web application you may want to put database related code into a separate project. I find it good for separating concerns.

In a previous post I covered using .Net Core Generic Host for stand alone projects, but the same applies to ASP.Net Core applications as they also use Generic Host.

By database related code I mean things such as database context, table models and database related config.

Create project

Create a new Class Library. Usually this can be .NET Standard, but .NET Core will work just fine. If you plan to share project with .Net 4.x you may want to go with .NET Standard.


Make sure you have selected your new database-project.

Create test database



Adding new project to Startup.cs

Create a DatabaseStartup.cs that functions as you would normally expect from Startup.cs, but containing only database specific things:

Every method in Startup.cs should execute a corresponding method in DatabaseStartup.cs:

If you need config object for database registered then you also need to create DatabaseConfig.cs:

Scaffolding & Migration

Install-Package Microsoft.EntityFrameworkCore.Tools

Add-Migration -Project Tedd.CoreWebExample.Database -StartupProject Tedd.CoreWebExample.WebUi “InitialMigration”

Update-Database -Project Tedd.CoreWebExample.Database -StartupProject Tedd.CoreWebExample.WebUi

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: