Setting up Entity Framework With Code First and Code Migrations

The Entity Framework is a Microsoft created framework that allows developers to easily retrieve data from the database.

From Microsoft:

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

Entity Framework supports the Code First approach. That means you can develop an application focusing on your code. You can define your models and the framework will generate the database from it. You can work with a database without writing a single SQL line.

The first step is to install the Entity Framework from the Nuget Package Manager.

Entity Framework

After it is installed we can start coding with it. Let's say we want to store our system Users and allow them to create new Posts. So our models in this scenario will be User and Post.

  1. public class User    
  2. {    
  3.     public User()    
  4.     {    
  5.         Posts = new List<Post>();    
  6.     }    
  8.     public int ID { getset; }    
  10.     public string Name { getset; }    
  12.     public virtual ICollection<Post> Posts { getset; }    
  13. }    
  15. public class Post    
  16. {    
  17.     public int ID { getset; }    
  19.     public string Name { getset; }    
  21.     public string Text { getset; }    
  23.     public User Owner { getset; }    
  24. }  
Whenever we use Entity Framework we create an instance of a DbContext and access the database using it. To use our models we must tell Entity Framework that they belong on the data context. To do that we can inherit from DbContext and add properties of DbSet<T> to it.
  1. public class ApplicationContext : DbContext    
  2. {    
  3.     public ApplicationContext()    
  4.         : base("EntityFrameworkDemo")    
  5.     {    
  7.     }    
  9.     public DbSet<User> Users { getset; }    
  11.     public DbSet<Post> Posts { getset; }    
  12. }   
By doing it we are basically saying that our database has the two tables “Users” and “Posts”.

The DbContext constructor in this case is taking a string parameter that is specifying the database name it will create. It is also possible to send a Connection String name and it will automatically resolve from the config file.

Finally, to test our little setup, we can build a quick block of code and see what happens.

In the following example I will create two Users and two Posts. Each post has an owner.
  1. static void Main(string[] args)    
  2. {    
  3.     using (var db = new ApplicationContext())    
  4.     {    
  5.         var user1 = new User { Name = "Bruno" };    
  6.         var user2 = new User { Name = "Michels" };    
  7.         db.Users.Add(user1);    
  8.         db.Users.Add(user2);    
  9.         db.SaveChanges(); // commit changes    
  12.         var post1 = new Post { Name = "Entity Framework", Text = "Example using EF" };    
  13.         var post2 = new Post { Name = "Another post", Text = "Another example using EF" };    
  15.         post2.Owner = user2;    
  17.         user1.Posts.Add(post1);    
  18.         db.Posts.Add(post2);    
  20.         db.SaveChanges(); // commit changes    
  21.     }    
  22. }   
A SELECT * FROM Users returns:

Users returns

A SELECT * FROM Posts returns:

Posts returns

We can see that Entity Framework automatically created the database and tables for us, along with primary keys, foreign keys and everything we need. We didn't write a single line of SQL code.

Now let's look back at the code and retrieve data instead. Let's say we want to get all posts by a user id. In our Post class we don't have the user id, only the User object, and as you could see Entity Framework generated a column called Owner_ID for us. We can change it by adding the following: 
  1. public int OwnerID { getset; }   
To our Post class, by convention, Entity Framework will see that the name matches with the owner property and automatically use it as the index instead of generating one.

If we try to run our application we will get an error saying that the model changed since it was last created. This is because we changed the database, but since it already exists, Entity Framework can't re-create it.

We can either drop the database and let it create again or we can use Code Migrations.

Code Migrations are automatically generated files that know how to update the state of the database. To use them we need to open the Package Manager console under View > Other Windows, then type:


This will allow migration files to be created. We can then add a migration to our latest changes by typing:
  1. Add-Migration <Name>  
And finally update the database by typing:


Now that our database has been updated we can use it again.


Notice that there is a Configuration file. It is created when you Enable-Migrations. You can change it to set:
  1. AutomaticMigrationsEnabled = true;   
This allows you to change your models without having to create migrations manually. But you will still need to update the database manually by typing Update-Database.

Let's change our application to retrieve all posts from a user given and ID.
  1. static void Main(string[] args)    
  2. {    
  3.     using (var db = new ApplicationContext())    
  4.     {    
  5.         var posts = db.Posts.Where(o => o.OwnerID == 1).ToList();    
  6.     }    
  7. }    
retrieve all posts


Up Next
    Ebook Download
    View all
    View all