[EN] Entity Framework Core – Code First migrations

In this post I want to show you how to create new database using Entity Framework Core – Code First migrations approach.

codefirst

I have project ELP.Model in which I defined few entities. I want to create database from it. It is approach called Code First. This is how looks one of my entity

To be able to enable migration and create database, we need to create Context. My Context Class looks like this

We need to install few packages before we start with actual migration.

To do it, open Package Manager Console (In VS Tools-> Nuget Package Manager -> Package Manager Console) set Default Project to your target project and install packages. Make sure to install the newest versions or the same versions for all.

To enable migrations in our project first we need to type in the same console Add-Migration MigrationName

and here is surprise. Not so easy man. I missed something. Yes exactly, we need to add implementation of IDbContextFactory<ELPContext>

1

This class should look like this:

Another Try to Add Migration and … another error…

2

What da… !? It looks like it is an issue in EF Core v 1.1.0. Work around for it is to change version to 1.0 :/ To do it we need to modify TargetFramework in csproj file from netcoreapp1.1 to netcoreapp1.0

3

4

Another try

Uff now everything works fine.

5

Take a look into Solution Explorer. Here we have new classes and Migrations folder.

6

The last step is to execute Update-Database command in Package Manager Console.

Fortunately this time it worked for me in first try. I didn’t expect it will be so easy 😉

To verify it, open SQL Server Object Explorer and check it. It should create new database.

7

Yeah, we have created database, nice. Now we can add something to it 🙂

One comment

  1. Pingback: dotnetomaniak.pl

Comments are closed.