Entity Framework Core is an Object Relational Mapper (ORM) for ASP.net Core projects, really easy to use and to get up and running really quickly.
An important reason to use an ORM is to enable an object-oriented business model and still be able to store and query 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.
Update .net core 2.1
Entity Framework Core 2.1 added new seeding and migrations features.
Contrary to the previous versions of Entity Framework Core creating migrations from external assemblies is now even easier.
Often developers will aim to ensure their Database layer is entirely separate from business logic. In a lot of cases, they will also like to have their Database Entities and Domain entities as separate entities preferring to Map between 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 and
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.
- A huge reduction in code.
- Takes care of vendor-specific code by itself.
- Cache Management – Entities are cached in memory thereby reducing the
loadon 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
We’ll also add a reference
.In our case we are going to use Microsoft SQL Server 2017,
So let’s go ahead and add a reference to those packages too.
We can now create a barebones Database Context.
We’ll now create a new project which we’ll use to create a Database Entity objects we’ll call it rather unimaginetively
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
For the sake of example, We’ll create 3 additional classes:
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,
We do this in order to try and minimize the use
Magic Strings or numbers
To learn more about minimising the use of Magic Strings and Numbers within your code, I recommend reading Java By Comparison: Become a Java Craftsman in 70 Examples. Although the book is mostly about Java, you’ll find that many of the suggestions pertain just as much to C#
We’ll declare a constant string
Api.Database.csproj to ensure the 2 Nuget Packages have been added.
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.
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
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 curious, who want to take a look and examine the SQL Scripts that will be generated to create the migrations you can use
To view the SQL script your Migrations will use for your specific Database environment.
Check out the full list of Migration Commands
Create Entity Framework Core Migration
Open a Terminal window and navigate to the folder containing Api.Database.csproj i.e.
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
This will create the migration. Notice
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 make use of Microsoft SQL Server, so I will also need to add the following Nuget Packages to the API Project
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.
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)
- The Builder Pattern .net core - May 1, 2019
- Book Review: The Lean Startup - April 28, 2019
- Using Serverless Framework Environment Variables .net core Lambda - April 25, 2019