DropCreateDatabaseAlways Seed not called

11,591

Solution 1

In my situation, Seed was not called because I had enabled migrations. When I removed migrations it worked. http://entityframework.codeplex.com/workitem/1689

Solution 2

The Seed method will be called once you send the first SQL query to your database, not in your Application_Start. For example:

using (var ctx = new MyContext())
{
    var rolesCount = ctx.Roles.Count(); // should return 2
}
Share:
11,591
Justin Chmura
Author by

Justin Chmura

Software Engineer for the City of Scottsdale

Updated on June 04, 2022

Comments

  • Justin Chmura
    Justin Chmura almost 2 years

    I'm having an issue getting the Seed method to be called on my custom Database initializer. I'm using EF 5.0 and have the following code:

    public static class MyDatabase
    {
        public static void Initialize()
        {
            Database.SetInitializer(new MyInitializer());
        }
    }
    
    public class MyInitializer : DropCreateDatabaseAlways<MyContext>
    {
        protected override void Seed(MyContext context)
        {
            base.Seed(context);
            context.Roles.Add(new Role
            {
                ID = 1,
                Name = "User",
            });
            context.Roles.Add(new Role
            {
                ID = 2,
                Name = "Admin",
            });
            context.SaveChanges();
        }
    }
    

    These two classes exist in a separate class library from the MVC app. In the Global.asax, I call the Initialize() method:

    MyDatabase.Initialize();
    

    The database gets created just fine, it's just the Seed(MyContext context) method isn't called and no data gets put into my database.

  • Justin Chmura
    Justin Chmura over 11 years
    I am sending queries to the database. This I can confirm using Intellitrace. In the layout, I'm populating a dropdown with a list of data that always comes up empty. I'm also attempting to save a user to a role that doesn't exist.