EF Code First - sowing after deletion and then creating a database

I am trying to get EF Code First to reinitialize a database. My first thoughts were to call:

dbContext.Database.Delete();    
dbContext.Database.Create();

This creates a new database, but the seeding strategy (using Database.SetInitializer <>) is ignored. I do this above in the Application_Start method. Any ideas?

I also tried:

dbContext.Database.Initialize(true);
+5
source share
3 answers

One option is to create your own DatabaseInitializer, which inherits from DropCreateDatabaseAlways.

An example of this might be.

public class MyInitializer : DropCreateDatabaseAlways<EmployeeContext>
{
    protected override void Seed(EmployeeContext context)
    {
        context.Employees.Add(new Employee() {FirstName = "Marcy"});
        base.Seed(context);
    }
}

public class EmployeeContext : DbContext
{
    static EmployeeContext()
    {
        Database.SetInitializer(new MyInitializer()); // using my own initializer
    }

    public IDbSet<Employee> Employees { get; set; }
}
0
source

Here is what I did to overcome this:

  • Add a flag to your context initializer

    public bool WasSeeded = false;

  • . AddOrUpdate upsert, .. , :

    context.Students.AddOrUpdate

true

  • , , :

    if (! initializer.WasSeeded) {    initializer.SeedAndUpsert(); }

0
Database.SetInitializer(new CustomInitializer()); //CustomInitializer contains the overriding Seed method

using (var context = new CustomDatabaseContext())
{
    context.Database.Initialize(force: true);
}
0
source

All Articles