Why isn't the seed method called?

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

Here is my code DbContext

:

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

        }
    }   
}

      

In my method Application_Start

, I have the following code:

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

      

When I access any of the objects DbSet

in the class CanFindLocationDatabaseContext

, the seed method fails. There is no database before checking the seed test code.

The database is created and tables are created, but the seed method is not called and there is no 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 CanFindLocationDatabaseContext

.

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

Thanks in advance.

+3


source to share


1 answer


The database will be loaded and created only on access, so if you need it for seeding you need to either refer to the context in Seed () or 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

+2


source







All Articles