关于生成数据库和播种的困惑

时间:2012-05-28 10:15:49

标签: ef-code-first code-first entity-framework-4.3 ef-migrations

我首先使用实体​​框架代码 我也有数据播种代码

现在,当我运行我的应用程序时,我的数据库会生成,但不会被我的虚拟数据播种。 我必须再次运行实体框架才能填充所有数据。

知道为什么以及如何解决这个问题,所以我不需要运行我的应用程序2x来获取数据库和数据?

日Thnx

我的上下文定义文件是:

 public class Context : DbContext
    {
        public DbSet<Task> Tasks { get; set; }
        public DbSet<Agency> Agency { get; set; }

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
        base.OnModelCreating(modelBuilder);
     }
    }

这是我的播种文件

public class Configuration : DbMigrationsConfiguration<Context>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }

    protected override void Seed(Context context)
    {
        GenerateTasks(context);
        context.SaveChanges();
    }

    private static void GenerateTasks(Context context)
    {
        if (context.Task.Any()) return;
        context.Task.Add(new Task() { Name = "Received" });            
    }
}

创建数据库的钩子是:

  Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
  var context = new Context();
  context.Database.Initialize(true);

2 个答案:

答案 0 :(得分:1)

如果您的应用是 ASP.NET ,并且是来自数据层的单独的程序集,那么您可以,而不是像您一样配置初始化,配置它直接在web.config中。也许这就是你问题的原因。

因此,如果它是一个ASP.NET应用程序,您可以尝试以下方法:

<强>(1)

对此进行评论:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
var context = new Context();
context.Database.Initialize(true);

<强>(2)

在web.config中,在结束 / configuration 标记之前的末尾插入此权限:

<entityFramework>
<contexts>
  <context type="**fully-qualified name of your context class**,
                 **assembly name of your context**">
    <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[**fully-qualified name of your context class**, **assembly name of your context**],
                               [**fully-qualified configuration type**, **assembly name of your context**, Version=1.0.0.0, Culture=neutral]], EntityFramework"/>
  </context>
</contexts>

其中完全限定的配置类型是您的迁移配置类(类似[...] Context.Migrations.Configuration)

我在自己的项目中使用这种配置方法并且效果很好!

答案 1 :(得分:0)

这是真的。调用context.Tasks.Find(1)然后它将命中数据库。 EF代码优先使用这个技巧推迟每件事。这样,应用程序的启动时间似乎更快。 (但实际上并非如此!)

相关问题