Entity Framework 6 Code-First On the run

It’s a quick topic about Entity-framework 6 code first approach.

Code first approach is the most used approach, it’s easy and controllable, It allow developers to write the code first and then generate database from the code, so they will focus on the domain and let .Net take care of data layer also it allow developers to control database versions and history. Also it’s very popular cause most programmers don’t like any kind of designers and defining mapping in EDMX.

Now the quick steps in order to start coding using Entity Framework code-first are a 4 steps only:

How to apply code-first for the first time:

1- write your models for example your POCO classes:

First we will assume that we have a solution that contains 3 projects one is the UI, second is our entities (Domain) project and another project is our Data project which contains our DbContext.

Models is our domain models for example we have 3 entities: Player, Group, PlayerTool:

public class Player
public int Id { get; set; }
public string Name { get; set; }
public Group Group { get; set; }
public int GroupId { get; set; }
public List<PlayerTool> ToolOwned { get; set; }

2- Enable migration and this can be done from visual studio package manager by choosing the project that contains your DbContext then type:


3- Add migration and for the first time adding migration will user DbMigration APIs to write migrations

4- update database and this will make 2 things apply changes in Up() method to database and add hash for model to __MigrationHistory table

To be continue as soon as possible!