.net core tutorials

Using EF Core in a Separate Class Library project

Entity Framework Core is an Object Relational Mapper (ORM) for ASP.net Core projects. It’s. really easy to use and you can get up and running with it really quickly.

An important reason to use an ORM is so that you can have a rich, object oriented business model and still be able to store it and write effective queries quickly against a relational database.

When using Entity Framework Core there are a couple of ways to Run Migrations from a Separate class library. In this post I will walk you through the process of running EF Core migrations from NET Standard Class Library.

Code available on Github

Often developer aim to ensure their Database layer is entirely seperate from business logic. In a lot of cases, they will also like to have their Database Entities and Domain entities as seperate entities prefering to Mapping being these, and only use Domain entities in the within their business logic.

These are best practices and software design patterns defined in Patterns of Enterprise Application Architecture (The Addison-Wesley Signature Series) and Domain-Driven Design: Tackling Complexity in the Heart of Software

Featured Book Review


Using an ORM, you should ensure to make your model objects as simple as possible. Be more vigilant about simplicity to make sure your model objects really are just Plain Old Data Objects (PODO), otherwise you may end up wrestling with your ORM to make sure the persistence works like you expect it to, and it’s not looking for methods and properties that aren’t actually there.

The Benefits of using ORM’s include:

  • Facilitates implementing domain model pattern.
  • Huge reduction in code.
  • Takes care of vendor specific code by itself.
  • Cache Management — Entities are cached in memory thereby reducing load on the DB.

To further abstract your Database logic from your business logic you may want to implement what is known as the Generic Repository Pattern



Add Database Class Library Project

We make use of solution and projects files in the source code, so if you are not familiar with working with solution files using .net core you may want to check out my post – Creating and Editing Solutions files with .net core CLI.

I’ll add a new class library project, primary purpose of this project is to create Database Context object which well share across a couple of projects.

Rename the generated class to ApiContext.cs

We’ll also add a reference to Microsoft.EntityFrameworkCore. In the terminal window you can use dotnet add package Microsoft.EntityFrameworkCore. In our case we are going to use Microsoft SQL Server 2017, as database server.

So lets go ahead and add a reference to those packages too. dotnet add package Microsoft.EntityFrameworkCore.SqlServer and we will also need dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet

We can now create a barebones Database Context.



Database Entities

We’ll now create a new project which we’ll use to create a Database Entity objects we’ll call it rather unimaginetively Api.Database.Entity.

The default class created via the project template we’ll rename to BaseEntity.cs and we’ll add some basic entity properties we need.

We’ll also add an additional folder to the Entity Project and call it Threats.

For the sake of example, We’ll create 3 additional classes:

  • Status.cs
  • Threat.cs
  • ThreatType.cs

To View the properties of the file check the source code repository



Add Reference to Entity

We now need to add a reference for our Entity Project project to the Database Project.

For the purpose of my project I will create a static class which will be used to store all our constant string declarations, called DBGlobals . We do this in order to try and minimize the use of Magic Strings in our code and we have one consistent string we can use throughout our library.

We’ll declare a constant string SchemaName

View Code
Review the Api.Database.csproj to ensure the 2 Nuget Packages have been added.

  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.Tools.DotNet

We are now ready to update, ApiContext.cs with additional logic

Our EF Core work is now complete. We have a basic Schema, and we have developed our Context, for the most part we are done. All we need to do now is create the Migration to get our Database up and running.

I will illustrate how we will make use of SQL Server 2016, running within a Docker Container to enable testing of the Migration Scripts. I won’t discuss how to get started with SQL Server and Docker. Microsoft do a pretty good job of explaining Connect to SQL Server on Linux

Check out install Docker for Ubuntu Developers



Define Migrations Assembly

Once you have created your EF Database project and have referenced it from your application project. You can use the API extensions that I believe have been shipped with EF Core 2.1. I only stumbled across them then other day while setting up a new project.

The DbContextOptionsBuilder now seems to have a new MigrationsAssembly method which you can pass the name of the assembly which you would like to include the Migrations in. You define this by adding options when add the context configuriton during the ConfigureServices in your application Startup.cs

Once this is done you can now, as in my case I tend to the terminal window in Rider : cross platform .net IDE , to navigate to my project directory and simply use:

For the curios you can also use

To view the SQL script your Migrations will use for your specific Database environment. Check out the full list of Migration Commands



From this point on is the legacy implementation.

Create Dummy Project

Once you have your SQL Server up and running whichever way you choose. We will need to create another DummyUI console project. The reason for this is a little quirk in how EF Core works, is that you are unable run Migrations against Class Library projects.

We will create a Dummy Console Project, that will be used as the Start Up project for the Migration task. This project does not form part of your project, it’s only purpose is to assist in the creation of your Migrate scripts. It is not required as part of a deploy or even as part of your build process.

The purpose of this project is a developer only utility, in order to help with the creation of Migration Scripts.

The migration scripts will be generated to your Migrations folder in your project or wherever you have defined it. In the case of my project that will be in the Api.Database project.

We will need to add a couple of references to the DummyDB

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.Tools.DotNet

We also need to add project references to our Api.Database & Api.Database.Entity

We need to add an Additional class to our Api.Database pjoject



Create Entity Framework Core Migration

Open a Terminal window and navigate to the folder containing Api.Database.csproj i.e. cd Api.Database.

If you’re using Visual Studio Code you can use the Integrated Terminal Window, or in I like to use Whack Whack Terminal – a terminal emulator for Visual Studio 2017, so you can click on the project then use ctrl + \ & ctrl + \ to open a terminal window. For the purpose of this post we will focus on using Visual Studio Code.

Once you have a terminal window open, in the directory of your database project , you can execute dotnet ef --startup-project ../DummyDB migrations add [Migration Name] to initiate the migrations. Notice the --startup-project which we are providing the directory path to our DummyDB project.

When setting up an EF Core project ensure the CSproj file has the following references

Add reference the EF Library

In order to make use of our seperate library we will need to edit the StartUp.cs to add our Context to the Services Collection.

In my case I am making use of Microsoft SQL Server, so I will also need to add Nuget Package Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.SqlServer.Design to the Api Project.



Summary

Using the above technique you can encapsulate all your database logic within a separate class library project that you can share across multiple projects. You will not be dependent on any project to build or execute any database changes, the result being all your database activities are encapsulated and constrained to one library.

To expand further on this example, you may want to read How to seed your EF Core Database, to find out how you can further isolate and manage your database concerns using EF Core.

Watch The Video

After receiving a few questions about this post, I thought I would create a quick video together to walk through the process and explain the code I use in this example. There may be some additional content with further explanations in the video that I have not totally covered in this blog post.

The video is totally unscripted and I am basically providing and explanation by walking through the implementation of the pattern above. If you need any further explanation, or are still unclear please do just leave a comment and I will attempt to explain further.

 

Gary Woodfine

Freelance Full Stack Developer at threenine.co.uk
Helps businesses by improving their technical proficiencies and eliminating waste from the software development pipelines.

A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.

Latest posts by Gary Woodfine (see all)

Affiliate Disclaimer

Disclosure: Please note that some of the links included in the blog posts are affiliate links, which means I will earn a commission if you decide to make a purchase.

I only include affiliate links to products, services and companies that I have personal experience and have actually used. I only recommend them because they are helpful and useful, not because of the small commissions I make if you decide to buy something.

Please do not spend any money on these products unless you feel they are relevant, suitable and will help you achieve your goals.

Buying anyone of these products and the commisions earned will not make me an overnite multi millionaire, but they will help to cover the hosting costs and compensate for the countless hours and effort I put in to create meaningful and valuable free content I provide to help others succeed.

You've also undoubtedly noticed that I also use various advertising networks - unless of of course you're using an Ad blocker, this is also an attempt to reduce my monthly deficit I experience in providing free relevant, valuable and on occassion insightful content for the benefit of others.

I only really make some money if people click on the ads, unless of course you consider 1c per 1000 impressions real money!

Bear in mind just how many impressions I need to make before I can cover my £20 hosting costs a month!

If you are using an adblocker and guilt stricken you can of course donate using any of the buttons below, but I won't be holding my breath.


Buy me a coffeeBuy me a coffee
π