实体框架6表未使用CreateDatabaseIfNotExists创建

时间:2015-01-09 14:50:51

标签: entity-framework

将初始化设置为CreateDatabaseIfNotExists时, 我注意到如果数据库存在但表格没有,则不会创建。

在这种情况下,DB有多个不相关的表,我需要EntityFramework来创建表(如果它不存在),或者使用它(如果它存在)。 DropCreateDatabaseAlways显然不是一个选项,因为它会破坏同一数据库中的其他表。

3 个答案:

答案 0 :(得分:1)

 public MyDbContext()
            : base("DefaultConnection")
        {
            Database.SetInitializer(new SeedMyDbContext());
            Configuration.LazyLoadingEnabled = true;
        }

 public class SeedMyDbContext : CreateDatabaseIfNotExists<MyDbContext>
        {
            protected override void Seed(MyDbContext context)
            {
               //Your code goes here (dummy data seeding)
               base.Seed(context);
            }
        }

我正在使用这样的创建表。

还有update-database的迁移。我希望这会奏效。

答案 1 :(得分:0)

我认为您无法使用CreateDatabaseIfNotExists初始化程序执行您所做的事情(根据您的评论)。您可能需要创建自己的自定义初始化程序,或者可能需要使用迁移。

答案 2 :(得分:0)

使用初始化程序MigrateToLatestVersion添加新表等。 例如

  Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, MyMigrationConfiguration>());
  myContext.Database.Initialize(true);    

迁移Config Class ....

  // use a base migration config class to control

public class MyMigrationConfiguration : BosBaseMigrationConfiguration<BosSystemDbContext> {
    // specific action for this context and migration??? maybe...
  }        


    // keep it consistent here
  public abstract class MyBaseMigrationConfiguration<TContext> : DbMigrationsConfiguration<TContext> 
    where TContext  : DbContext{

    protected  MyBaseMigrationConfiguration() {
        AutomaticMigrationsEnabled = true;  // you can still chnage this later if you do so before triggering Update
        AutomaticMigrationDataLossAllowed = true; // you can still chnage this later if you do so before triggering Update

    }
    protected override void Seed(TContext context)
    {
        base.Seed(context);  // but i dont like this approach to seeding
    }

}