DotNetCore

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.

That being said it does have some quirks and idiosyncracies which may catch you off guard if you’re not aware of them. I have found keeping an eye on Julie Lermans blog really helps, she seems to have a knack for finding the edge cases and solutions when it comes to Entity Framework in general.

In the particular example I want to highlight in this blog post, is something I uncovered when developing my series of blogs post, regarding developing an ASP.net Core API for my Stop Web Crawlers WordPress Plugin.

I wanted to keep my Database layer was seperate from API logic, in that I didn’t really want to include my Database Enity classes etc within my API code.

Potentially I will be developing a further two micro service type API’s which may use the same Database Schema but not necessarily the same database server.

Can’t wait to see it in action ?

Check out the code on GitHub

 

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



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.
π