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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With