Seeding a Database With EF4.1 Code First

Based on an email in my inbox, I wanted to point out the key to overriding the Database Initializer that seeds a newly generated database when you use EF 4.1 code first.

The Seed method takes whatever you put in the context and saves it to the database. So in your override, you don’t need to call SaveChanges but you DO need to be sure to call the base Seed method at the end.

Here’s some sample code that I’m using in the code first & EF 4.1 videos & articles  I’m working on for MSDN (3 online, more coming). This particular one is targeted for when a model change causes the database to be dropped and recreated.

 

public class BlogContextInitializer
: DropCreateDatabaseIfModelChanges<BlogContext> { protected override void Seed(BlogContext context) { //create sample data and attach it to the context.
   new List<Blog>
   {
    new Blog { BloggerName = "Julie", Title = "My Code First Blog",
               BlogDetail=new BlogDetails{Description="About code first",
DateCreated=new System.DateTime(2011,3,1)} ,Posts=new List<Post>{
new Post {
Title="ForeignKeyAttribute Annotation",
DateCreated=System.DateTime.Now,
Content="Mark navigation property with ForeignKey"}} }, new Blog { BloggerName = "Ingemaar", Title = "My Life as a Blog", BlogDetail=new BlogDetails{
Description="Random tidbits",
DateCreated=new System.DateTime(2011,1,1)}}, new Blog { BloggerName = "Sampson", Title = "Tweeting for Dogs", BlogDetail=new BlogDetails{
Description="How to tweet without opposable thumbs",
DateCreated=new System.DateTime(2011,2,1)}} }.ForEach(b => context.Blogs.Add(b));
   base.Seed(context);  }
}

Somewhere in your startup code, e.g., global.asax in a website, main in an app, you also need to be sure to tell EF to use this overload:

System.Data.Entity.Database.SetInitializer(new BlogContextInitializer());

 

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.