Introduction
This article is a part of a series of articles I write about Entity Framework Code First. You can find my previous article here:
Now, if we know how to create a database using Code First, we could want to add
some data during the database creation in order to have some useful data to test
our interface. We can write a SQL script that will provide data in the database but EF Code First allows us to do it in an easy way, so let's try it.
Using the code
The data would be defined in an initializer class:
public class EfInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
protected override void Seed(MyContext context)
{
var persons = new List<Person>
{
new Person {LastName = "Smith", FirstName = "John", BirthDate= DateTime.Now.AddDays(-1080)},
new Person {LastName = "Doe", FirstName = "James", BirthDate= DateTime.Now.AddDays(-1070)}
};
persons.ForEach(p => context.Persons.Add(p));
var projects = new List<Project>
{
new Project {Name = "Project 1", Manager = persons[0]},
new Project {Name = "Project 2", Manager = persons[0]},
new Project {Name = "Project 3", Manager = persons[1]}
};
projects.ForEach(p => context.Projects.Add(p));
context.SaveChanges();
}
}
Once the data has been defined, we have to tell our context to initialize the database with our data. To do that, go in the
Program.cs class and add the following line in the Main
method:
Database.SetInitializer<MyContext>(new EfInitializer());
This line is really simple to understand. We are telling our database to use the class
EfInitializer
to initialize itself.
Now you can run your console application and see that data is added to the database at startup. First we run the program:
Everything went fine. Let's see our database:
Good news: Our data is there!!!
Hope this will help you during your development.
History
- June, 2012: First post.
- June, 2012: Updated the post with links to my previous articles