user65439 user65439 - 2 months ago 15
C# Question

Seed method not called, Entity Framework 6

I have a

DatabaseInitializer
class

public class DatabaseInitializer : CreateDatabaseIfNotExists<DatabaseContext>
{
protected override void Seed
(
DatabaseContext databaseContext
)
{
// Seed the hash methods.
var defaultHashMethod = new HashMethod
{
Description = "Default",
CreateDate = DateTime.Now
};

databaseContext.HashMethod.Add(defaultHashMethod);

databaseContext.SaveChanges();
}
}


In my DatabaseContext class I set the initializer

public DatabaseContext() : base("DatabaseContext")
{
InitializeDatabase();
}

private void InitializeDatabase()
{
Database.SetInitializer(new DatabaseInitializer());
if (!Database.Exists())
{
Database.Initialize(true);
}
}


As far as I can understand the seed method is only invoked once you perform an operation such as a query. My database is created successfully and I'm querying the table, but the seed method is never called.

Update:

It seems like the problem is caused because of a class that is
inheriting
from my
DatabaseContext
class, when using this class to perform database operations, the seed method is not called. When using my
DatabaseContext
class, everything works as expected

public DbSet<TestEntity> TestEntity { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

Answer

The only way I could get this to work was to call the seed method myself

Here are the methods for my DatabaseContext class

 public DatabaseContext() : base("DatabaseContext")
 {
    InitializeDatabase();
 }

 public DatabaseContext(string connectionString) : base(connectionString)
 {
     Database.Connection.ConnectionString = connectionString;
     InitializeDatabase();
 }

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
 }

Here I changed my InitializeDatabase method from

private void InitializeDatabase()
{
    Database.SetInitializer(new DatabaseInitializer());
    if (!Database.Exists())
    {
        Database.Initialize(true);
    }            
}

to

protected virtual void InitializeDatabase()
{
    if (!Database.Exists())
    {
        Database.Initialize(true);
        new DatabaseInitializer().Seed(this);
    }            
}
Comments