Entity Framework Core Migrations

This article explains Entity Framework Core migrations and how to use the Table Attributes.

EntityFrameworkCore Migrations

Tools needed for the below demo:

VS 2017 
.NET Framework
.NET Core 2.1
AdventureWorksDB - you can download it from the Microsoft site.

Packages to be installed are -

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools.DotNet
So, let us start now. 
 
Take a .NET Core Console Project (EFCoreSample) and run the below command from Package Manager Console.
 
Scaffold-DbContext "Server=.\;Data Source=INHYLDEBASISHK;Initial Catalog=AdventureWorksLT2017;Integrated Security=False;Trusted_Connection=True;MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -o Entities
 
Note that in EF Core, we don't have the edmx concept.

Output

The output of the above query will be an Entities folder with all the entities (Tables) of AdventureDB and contextClass.
 Entity Framework Core Migrations
 
For enabling the migration, run the below command in Package Manager Console (PMC).

add-migration migrationName

This adds a migration folder with 3 files. For example, I have run the command add-migration ProductModel. Look into the output on my system.

Entity Framework Core Migrations 
 
Naming
  1. Timestamp_migrationname.cs
  2. Timestamp_migrationname.designer.cs – metadata file , contains information used by EF core
  3. <contextclassname>modelsnapshot.cs
Timestamp_migrationname.cs
 
This is the main migration file which includes 2 methods, up and down. The Up method includes the code for creating DB objects and the down method includes code for removing the DB objects.
 
<contextclassname>modelsnapshot.cs
 
This takes the snapshot of a current model. This is used to determine what will be changed when creating the next migration.
 
Scenario
 
Suppose we want to add a record to the product Model table. We can create database scripts for the same requirement but here, instead of creating a database script, we will create migrations using EF Core.
  1. using System;  
  2. using Microsoft.EntityFrameworkCore.Metadata;  
  3. using Microsoft.EntityFrameworkCore.Migrations;  
  4.   
  5. namespace EFCoreSample.Migrations  
  6. {  
  7.     public partial class ProductModel : Migration  
  8.     {  
  9.         protected override void Up(MigrationBuilder migrationBuilder)  
  10.         {  
  11.             var guid = Guid.NewGuid().ToString();  
  12.             migrationBuilder.Sql(@"  
  13.                 IF NOT EXISTS(SELECT * FROM [SalesLT].[ProductModel] WHERE[Name] = N'SpeedoMeter') BEGIN  
  14.                 INSERT [SalesLT].[ProductModel] ([Name], [CatalogDescription], [rowguid],[ModifiedDate]) VALUES   
  15.                 (N'SpeedoMeter',NULL,NEWID(),GETDATE())  
  16.                 END");  
  17.         }  
  18.   
  19.         protected override void Down(MigrationBuilder migrationBuilder)  
  20.         {  
  21.              
  22.         }  
  23.     }  
  24. }  

Now, we will update the database from Visual Studio PMC. Before updating, we need to map the entities model name with the database table name. In the below diagram, you can see that the table name is prefixed with schema name SalesLT.ProductModel but our entity name is ProductModel.

So, we have a concept called the Table attribute.

The Table attribute is applied to an entity to specify the name of the database table that the entity should map to. The above example specifies that the product model entity should map to a database table named SalesLT.ProductModel.

So, in the Attribute folder, we can add a DBTableAttribute class which inherits from TableArribute and take care of these conversions.

DBTableAttribute.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations.Schema;  
  4. using System.Text;  
  5.   
  6. namespace EFCoreSample.Attibute  
  7. {  
  8.     [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]  
  9.     public class DbTableAttribute : TableAttribute  
  10.     {  
  11.         public DbTableAttribute(string name) : base(GetTableName(name))  
  12.         {  
  13.             Schema = GetSchema(name);  
  14.         }  
  15.   
  16.         private static string GetSchema(string name)  
  17.         {  
  18.             var split = name.Split('.');  
  19.   
  20.             if (split.Length == 1)  
  21.                 return null;  
  22.   
  23.             return split[0];  
  24.         }  
  25.   
  26.         private static string GetTableName(string name)  
  27.         {  
  28.             var split = name.Split('.');  
  29.   
  30.             if (split.Length == 1)  
  31.                 return split[0];  
  32.   
  33.             return split[1];  
  34.         }  
  35.     }  
  36. }  

Adding the attribute to the ProductModel Entity : (present inside Entities Folder)

  1. using EFCoreSample.Attibute;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5.   
  6. namespace EFCoreSample.Entities  
  7. {  
  8.     [DbTable("SalesLT.ProductModel")]  
  9.     public partial class ProductModel  
  10.     {  
  11.         public ProductModel()  
  12.         {  
  13.             Product = new HashSet<Product>();  
  14.             ProductModelProductDescription = new HashSet<ProductModelProductDescription>();  
  15.         }  
Creating or Updating the Database

For updating the database, run the below command in Package Manager Console(PMC).

Update-DataBase 
  • The database command will create a database based on the context and domain classes and the migration snapshot.
  • When we run the update-database command after creating the first migration, a table also gets created in Db (_EFMigrationHistory) which will store all the names of the migrations, as and when they get applied to the database.
Entity Framework Core Migrations 
Entity Framework Core Migrations 
 
Whenever we run the update database command, it will apply all the migrations to the database.
 
Thanks!