EF Core in separate project

By | 2019-06-20

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.

Installing

Make sure you have selected your new database-project.

Create test database

TestElement.cs

TestDbContext.cs

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

[ To be continued ]

Leave a Reply

Your email address will not be published. Required fields are marked *