Seed method not called, Entity Framework 6

c# entity-framework

Question

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>();
}
1
13
8/27/2014 12:13:32 PM

Accepted 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);
    }            
}
8
2/19/2015 7:02:32 AM

Popular Answer

You need to call Update-Database from the Package Manager Console.



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