Entity Framework Migrations and Data Seeding

This article is a part of a multi-post article on Entity Framework Code First for web applications:

  1. Entity Framework Code First Entities and entity relationships
  2. What do you need to know about Entity Framework Data Context
  3. Entity Framework Migrations and Data seeding

This article is the second part of the posts. The first part talks about defining entities and relationships. The second part talks about the data context. You may find links to previous posts above. Let’s continue by talking about how to propagate changes to the database and seed the database with data for referential tables.

Entity Framework Migrations is a feature of Entity Framework to manage the reflection of changes in the code to the database structure. It compares the structure of entity classes and database tables to identify changes and write SQL scripts for implementing changes in the database.

To start using Migrations feature, we must first activate the tracking of changes in entity classes. Enabling Migrations can be done with a simple command which can be given through Package Manager Console (you may find it at: View->Other windows->Package Manager Console). In the console, you write the command Enable-Migrations (please note, this command may be different in versions of Entity Framework, my examples are using Entity Framework 6).


Before executing the command, please note to have the right project selected as the default project (in case you have an n tier architecture with data access layer on it’s own project).

After the command is executed, you will see a new folder appearing in the project structure, which holds the migration related files. As you add migration points, you will see files to be added to this folder with the name of migration point and its timestamp.


Inside the Migrations folder, you will also find a file named Configuration.cs. This file contains the initial configuration for the database, which we may use to populate some database tables with initial values and many other configuration tasks. A sample initialization can be done through the Seed method of the Configuration class:

In the example above, you may see two sample classes, PaymentType and Category, which refer to referential tables in database, being populated with initial values, and the context saving changes at the end. This happens every time we issue update to the database. To avoid duplicate entries, please use AddOrUpdate method to add entities, instead of just Add.

But, what do I mean by a migration point. As you develop, often you make several structure changes in the classes, you add new classes, you add properties to existing classes, refactor existing ones, etc. After you do a fix or complete e feature, you create a migration point which stores changes from previous migration point until now. We can create a migration point by executing this command:

PM>add-migration 'name of migration'

Each successful migration point will create a file in the Migrations folder named as timestamp_name_of_migration.cs. These points will help you if you want to go back to a previous state of the database structure, in case you want to roll back the developments.

One point to be clear, when you create a migration point, the changes are not yet pushed to the database. It is only when we execute command Update-Database that the Entity Framework tries to push changes to the database based on the connection string found in the config file. This MSDN article shows a more complete list of migration commands.

We might some times want to update the database ourselves and not let the Entity Framework do it on its own. We may ask Entity Framework to show us the script of changes. We can do this using the command Update-Database -Script. After the execution, we will have an SQL script with all changes pending to be executed in the database.


Entity Framework Migrations is an important feature which will allow you to adopt the database structure in agility as you develop the code. Changes you make are kept in history and if you would like, you may go back in history, track changes, or even revert back to some point in history. All this with an easy command line interface which is easily executed in the Package Manager Console. Find more info in the official documentation of Entity Framework.

What you need to know about Entity Framework Data Context

This article is a part of a multi-post article on Entity Framework Code First for web applications:

  1. Entity Framework Code First Entities and entity relationships
  2. What do you need to know about Entity Framework Data Context
  3. Entity Framework Migrations and Data seeding

This article is the second part of the posts. The first part talks about defining entities and relationships. You may find the first article in this link. Let’s continue by talking about the data context in the Data Access Layer.

Entity Framework enables us to abstract the data layer and communicate with the database for the Create, Read, Update, and Delete (CRUD) operations. We also defined the relationship between entity classes and database tables. Just as every table is enclosed inside a database, in Entity Framework, entities are enclosed inside a data context to abstract a database. The primary class that creates this context is the DbContext class of System.Data.Entity namespace. To abstract a database, we usually create a class representing our context which extends DbContext class. Let us suppose that we have a database called HumanResources and we want to connect to that database using Entity Framework. Our Entity Framework Data Context would look like this at beginning:

The DbContext class that we extend will allow us to define our database tables as sets of entities (DbSet<T>), and then, we can query the database and do all the CRUD operations using those sets. Entity Framework will convert all those actions we perform to SQL queries, execute them towards the database, and return us the results back. DbContext even offers these operations in synchronous and asynchronous modes.

From the previous post, we had defined two entities, Person and Country. Let’s define them inside our context.

We pluralize the names of the sets as they represent the table of persons/countries, so multiple records are represented.

The DbContext’s lifetime starts with the instantiation of the object and it will end when the object is disposed or garbage collected. If we want to manage the lifetime of the context, we can put it inside a using construct to dispose it when we are done. During the lifetime, it will also manage opening and closing of connections to the database. E.g.

In the example below, we have created an instance of the HumanResourcesContext. Inside the curly braces, we have queried the persons table to find the person with the id equal to 1 (db.Persons.find(1)). DbContext allows us to query the database using the name of the DbSet properties we have define (which point to database tables), but the actual query is not executed when we say like db.Persons. The queries are executed when we ask the context for concrete data, like in our example with finding the person with id equal to 1. Other forms that we ask the context for the data could be execution of ToList(), ToArray(), Single() methods.

When using with ASP.NET, we should create a context per request. If we do it, we should use using during the process of request, or if we do it using an Inversion of Control (IoC) container, we should define the initialization of our context class as per request.

There is one more important thing to note here. We queried the database without even specifying the connection string for the Entity Framework. How does it know where to connect? By default, it uses the default connection string in asp.net (found in web.config in versions prior ASP.NET 5) and make the connection using it. If you want to specify a specific connection string, e.g. if we have a connection string named myConnectionString defined in web.config, you may pass it to the constructor of DbContext like this:

or hardcode it if you want (I would not recommend it)


DbContext class allows us to create the data context of our database abstraction. It allows us to perform CRUD operations towards our database using code first approach without writing SQL queries.


Entity Framework Code First Entities and entity relationships

This article is a part of a multi-post article on Entity Framework Code First for web applications:

  1. Entity Framework Code First Entities and entity relationships
  2. What do you need to know about Entity Framework Data Context
  3. Entity Framework Migrations and Data seeding

It is not very often that I see web development tutorials focusing on db level with entities and their relationships. But, whatever web application you start working on, chances are you will need a database to store and read some information. In this post, I will try to give a short description of entities and how relations are created between them in the context of Entity Framework Code First, as the data access layer of a web application. Let’s see first what is Entity framework.

About Entity Framework Code First

Entity framework is Microsoft’s Object Relational Mapping (ORM) solution. It supports the communication between the code and the database, facilitating the development of the database structure (by generating DML code automatically), data access, and mapping the data between data sets and objects of our code. Entity framework enables us to develop the data access layer in three ways: database first, model first, and code first. The development of these methods have come in a progressive way, code first being the latest approach, and personally I would say, it is the most flexible one. It allows us to develop our database starting from the code. This gives us the possibility to think from the code’s perspective and enable us to structure our code as it fits best the application logic, not the database organization.

What is an Entity class?

Basically, entities are simple classes which represent entities of the application. Usually, every entity corresponds to a database table and in a way becomes the code representation of that table. An example might be, if we have the table persons in the database, we might have the class Person which represents a single record of that table. As the class represents a single person, it’s name is singular, and table’s name is usually in plural. Entity Framework by default take care about pluralization of table names by convention.

Creating an Entity class

Creating an Entity class is as simple as defining a class. Usually, classes have some properties inside them. Let’s model our entity class Person and see how it might look.

If we examine this class, we see that it has four properties, one integer number named Id, two string properties Name and Surname, and one DateTime property BirthDate, all representing personal details of a Person. Based on this definition of the Person class, Entity Framework creates persons table by examining these properties. We’ll go little deeper in the db creation in the next post.

Decorating Entities with validation attributes

Leaving Entities plain as in the example above will keep the code clean and readable. This kind of Entity is called a Plain Old CLR Entity or POCO for short. In some scenarios, it might be a good strategy to stick to POCO style and keep the Entities clean and put the validation code in some other partial classes or other parts of the code.

Entity framework gives us the possibility to decorate the classes and class properties with attributes, which are later used during the process of creating the database tables, and the client side validation in ASP.NET MVC. These decorations serve in two perspective: 1) they enable the Entity Framework to understand the property and gather metadata based on which will create the table columns; 2) they enable the client side validation of the input data for those properties to be done automatically.

Let us decorate the Person class with some attributes.

I have decorated Name and Surname properties. Now, both have the validation attribute [required]. Validation attributes are written inside brackets. The required attribute marks a property as required and this will translate as not null in the database. From this, we can see that we have made Name and Surname properties. The surname attribute is also decorated with a second validation attribute, which is MaxLength. MaxLength tells the maximum length (when the data type is string, this is the length of characters, when the data type is number, it is the length of numbers) of a column in a database. For more details about validation attributes please refer to this link on MSDN.

Defining relationships between Entities

The benefit of Code First approach of Entity Framework is that it allows you to define the whole database structure from within the code, this includes the relations between the entities as well. Let’s suppose that we have a lookup table countries which holds the list of countries. Now, we need to assign every Person entity a country. How can we do that?

We start by defining our Country entity first:

Now that we have our country entity, we can add the relation to the Person entity by modifying the class

By adding a reference to a Country entity we are telling the Entity Framework that we want to a relation between Person and Country entities. We have also quantified it as one to many, as one Person can have one country, but one country can be assigned to multiple persons, this definition will result to one to many relationship between Person and Country entities. The relationship diagram will look like this:


You may refer to this link for further details on defining relationships.


Entity Framework Code First approach will give you a good possibility to focus on code and and define everything from there. It gives you the flexibility to in a declarative form to define all the properties of database structure and change it accordingly as the code evolves. In the next posts, we will go through the defining the Data Context which is the backbone of the data access layer and after that we will focus on how to create the database from the code, feed it with data, and manage the changes in the database structure.