Click here to Skip to main content
15,886,518 members
Articles / Programming Languages / C#
Tip/Trick

[EF] Initialize database with data using Code First

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
16 Jun 2012CPOL1 min read 24.2K   192   1   4
How to add initialization data when configuring Entity Framework Code First.

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:

C#
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:

Image 1

Everything went fine. Let's see our database:

Image 2

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 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
France France
I'm coding in .Net since 9 years, most with ASP.Net and SharePoint and a little using WPF, MVC, Windows Phone 8 and WinRT technology.
I have learned so much reading others experience and tutorials, or tips so I try to do the same, keeping learning from others of course.
You can also find my blog here : http://sharemstips.wordpress.com/

Comments and Discussions

 
QuestionMore complex initialization Pin
snowburnt13-Aug-13 9:56
snowburnt13-Aug-13 9:56 
GeneralMy vote of 1 Pin
mrrandom15-Jun-12 10:08
mrrandom15-Jun-12 10:08 
GeneralRe: My vote of 1 Pin
Shahin Khorshidnia16-Jun-12 1:53
professionalShahin Khorshidnia16-Jun-12 1:53 
Of course because it's a tip/trick and has been sent as Tip
If we don't know that we don't know, we'll stay double ignorant for ever.

AnswerRe: My vote of 1 Pin
Nadege Rouelle16-Jun-12 2:00
Nadege Rouelle16-Jun-12 2:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.