我的Seed()方法永远不会在Code First EF 5中调用

问题描述 投票:12回答:2

我的Seed()方法从未被调用过。当我从包管理器控制台执行Update-Database时调用它,但从代码运行时从未调用过。如果删除我的数据库,则会创建所有表(因此我的迁移类已执行),但我的Seed()代码永远不会被调用。 MVC 4,实体框架工作5代码优先。

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....
}

组态:

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
}

可能有什么不对?

entity-framework ef-code-first code-first
2个回答
15
投票

所以原因是我需要在配置文件中指定我的自定义初始化程序:

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

之后,我的Seed方法被调用。


5
投票

请先参考接受的答案。 我只想为这个问题添加一个非常重要的注释。

我正面临着这个问题描述的同样问题(这引导我到这里)。但我使用的是CreateDatabaseIfNotExists而不是MigrateDatabaseToLatestVersion,即使应用了接受的答案,我的种子方法也没有执行。

我的问题如下:根据documentation of the for the Seed method:如果Database Initializer是以下之一,则不会执行SeedDbMigrationsConfiguration方法

如果您使用其中一种类型,则应创建自己的类,该类继承自其中一种类型,然后覆盖您自己的类中的种子方法。

在我的例子中,添加以下类解决了这个问题。

public class CreateNotifierDatabaseIfNotExists : CreateDatabaseIfNotExists<NotifierContext>
{
    protected override void Seed(NotifierContext context)
    {
        // the code of the seeding is go here
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.