.Net Core Code First Migration using Class Library

In this post we are going to elaborate how to work with EF code first migration using .Net core class library.

 Steps:

  1. Create a new project
  2. Create class library
  3. Install Entity Framework
  4. Create model
  5. Register context with dependency injection
  6. Create database

 

Let’s get started, create a new project with Visual Studio 2015

  • File > New > Project
  • From the left menu > Visual C# > Web
  • Choose ASP.NET Core Web Application (.NET Core)

 

ncore_0

Name it (MVCAngular2) & click OK. In our next step we will see how to create a .Net core class library & how to reference it to our application.

Add Class Library: SRC > Add > New Project

ncore_2

From the left menu > Visual C# > .Net Core

ncore_1

Choose Class Library (.NET Core), Name it (MVCAngular2.Models) & click OK.
Project.json default template

{
  "version": "1.0.0-*",

  "dependencies": {
    "NETStandard.Library": "1.6.0"
  },

  "frameworks": {
    "netstandard1.6": {
      "imports": "dnxcore50"
    }
  }
}

We need to add command line tools for EF Core that includes commands for Package manager Console.

"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

ncore_9

There is an unsupported issue of EF Core 1.0.0-preview2-final with “NETStandard.Library”: “1.6.0”. So that we have changed the target framework to netstandard1.6 > netcoreapp1.0
We have also specified the command line tool in tools section

"tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },

Finally after modification

{
  "version": "1.0.0-*",

  "dependencies": {
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },

  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  }
}

Packages will automatically restored to our project class library.

ncore_3

 

Install Entity Framework

Now let’s add folder for context & entities

ncore_4

 

Configuring DbContext
Let’s add a class to our context folder name it StudentContext which is inherited from the base class DbContext. We need to reference Entity Framework Core library to our class.

using Microsoft.EntityFrameworkCore;

Here in our context class we have passed a generic version of DbContextOptions with constructor argument of our context class.

public class StudentContext : DbContext
{
    public StudentContext(DbContextOptions options): base(options)
    {
    }
}

Using base keyword we have access the base class (DbContext) constructor to pass the options for the context from DbContextOptions.

base(options)

Let’s add Student model in Entities folder

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
}

Now in our DbContext Class let’s define the dbSets with Student model.
Finally DbContext class

public class StudentContext : DbContext
{
    public StudentContext(DbContextOptions options) : base(options)
    {
    }
    public DbSet Students { get; set; }
}

 

Register context with DI

Before register context let’s reference the library to our Web application project

  • Reference > Add Reference > Solution > MVCAngular2.Models

 

ncore_10

Open Startup.cs file, In ConfigureServices method we need to add AddDbContext method (which use Microsoft.Extensions.DependencyInjection) to register StudentContext as a service.

public void ConfigureServices(IServiceCollection services)
{
    var connection = @"Server=DESKTOP-4T79RA1;Database=EFCoreStudentDb;Trusted_Connection=True;";
    services.AddDbContext(options => options.UseSqlServer(connection));
}

First we have specified connection info

var connection = @"Server=DESKTOP-4T79RA1;Database=EFCoreStudentDb;Trusted_Connection=True;";

After that we have registered the context using the connection info.

services.AddDbContext(options => options.UseSqlServer(connection));

Here UseSqlServer() is an extension method that Configures the StudentContext to connect our SQL Server database.

 

Create database
Now let’s create a database by using migrations.

  • Tools > NuGet Package Manager > Package Manager Console
  • Type Add-Migration Initial to scaffold a migration press Enter
  • Type Update-Database to apply the new migration to the database.

 

Add-Migration Initial

ncore_5

ncore_6

Update-Database

ncore_7

Now open SSMS to explore our newly created database. As you can see from the below image.

ncore_8

Source Code: I’ve uploaded the full source code to download/clone , Hope this will help 🙂

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

5 thoughts on “.Net Core Code First Migration using Class Library”

Leave a Reply