Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My Seed() method is never called in Code First EF 5

My Seed() method is never called. It is called when I do an Update-Database from the Package Manager Console, but never when I run from code. If I delete my database, all tables are created ( so my migration classes are executed), but my Seed() code is never called. MVC 4, Entity Frame Work 5 Code First.

Global.asax:

protected void Application_Start()
{
  Database.SetInitializer<MyContext>(new DbInitializer());
}

DBInit:

internal class DbInitializer : MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration>
{
}

DBContext:

public partial class MyContext : DbContext
{
  public MyContext() : base("DefaultConnection")
  {
  }
  // public DBSets....
}

Configuration:

internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
{
public Configuration()
{
  // The constructor is actually called
  AutomaticMigrationsEnabled = false;
}

protected override void Seed(MyContext context)
{
   // My seed code, never called
}

What could be wrong?

like image 480
Magnus Johansson Avatar asked Nov 09 '12 19:11

Magnus Johansson


2 Answers

So the reason was that I needed to specify my custom Initializer in the config file:

  <entityFramework>
      <contexts>
        <context type="EFTest2.MyContext, EFTest2">
          <databaseInitializer type="EFTest2.Initializers.DbInitializer, EFTest2" />
        </context>
      </contexts>
      <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>

After that, my Seed method is called.

like image 90
Magnus Johansson Avatar answered Oct 15 '22 06:10

Magnus Johansson


Please first refer to the accepted answer.
I just want to add a very important note to this issue.

I was facing EXACTLY the same problem which described by this question (and this lead me to here). BUT I was using CreateDatabaseIfNotExists instead of MigrateDatabaseToLatestVersion and my seed method was not executed even after applying the accepted answer.

My problem was the following : According to the documentation of the for the Seed method : the Seed method of the DbMigrationsConfiguration will not be executed if the Database Initializer is one of the following

  • DropCreateDatabaseAlways
  • DropCreateDatabaseIfModelChanges
  • CreateDatabaseIfNotExists

If you are using one of those types, you should create your own class which inherits from one of those types, and then override the seed method in your own class.

In my case, adding the following class solved the problem.

public class CreateNotifierDatabaseIfNotExists : CreateDatabaseIfNotExists<NotifierContext>
{
    protected override void Seed(NotifierContext context)
    {
        // the code of the seeding is go here
    }
}
like image 24
Hakan Fıstık Avatar answered Oct 15 '22 07:10

Hakan Fıstık