DropCreateDatabaseAlways Seed not called

.net asp.net-mvc c# entity-framework

Question

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.

1
11
1/9/2013 5:33:25 PM

Popular Answer

Your database will be created later on when you use your context or You could always force it to create by using your context in the Application_Start() method in Global.asax.cs like:

  System.Data.Entity.Database.SetInitializer(new MyInitializer());
MyContext db = new MyContext();
db.Database.Initialize(true);
13
1/11/2013 9:48:56 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow