Why is the seed method not being called?

asp.net-mvc-5 c# dbcontext entity-framework-6 seeding

Question

I am coding a MVC 5 internet application and would like some help to execute the seed method to populate the database with some entities.

Here is my DbContext code:

public class CanFindLocationDatabaseContext : DbContext
{
    public class SystemInitializer : CreateDatabaseIfNotExists<CanFindLocationDatabaseContext>
    {
        protected override void Seed(CanFindLocationDatabaseContext context)
        {

        }
    }   
}

In my Application_Start method I have the following code:

System.Data.Entity.Database.SetInitializer<CanFindLocationDatabaseContext>(new CanFindLocation.Context.CanFindLocationDatabaseContext.SystemInitializer());

When I access any of the DbSet objects in the CanFindLocationDatabaseContext class, the seed method is not being executed. There is no database before I test the seed code.

The database is being created and the tables are being created, yet the seed method is not called and there is not data in any of the tables.

I also have the following code for identity 2.1 in the same project:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("CanFindLocationDatabaseContext", throwIfV1Schema: false)
    {
    }
}

The seed method is called for this DbContext class, but not for the CanFindLocationDatabaseContext.

Why is this, and how can I write my code so that the seed method is executed?

Thanks in advance.

1
4
5/19/2015 8:21:17 AM

Accepted Answer

The database is lazy loaded and will only be created when accessed, so if you need it for seeding you need to either access the context within the Seed() or you can add:

System.Data.Entity.Database.SetInitializer<CanFindLocationDatabaseContext>(new CanFindLocation.Context.CanFindLocationDatabaseContext.SystemInitializer());
var db = new CanFindLocationDatabaseContext()
db.Database.Initialize(true);   // force database creation

https://msdn.microsoft.com/en-us/library/system.data.entity.database.initialize(v=vs.113).aspx

3
5/19/2015 1:27:29 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