代码优先迁移和使用包管理器控制台命令进行升级一开始可能会有点混乱。
您可以使用初始化程序CreateDatabaseIfNotExists
, DropCreateIfModelChanges
, DropCreateDatabaseAlways
and to MigrateDatabaseToLatestVersion
查看界面IDatabaseInitializer<TContext>.
CreateDatabaseIfNotExists // is the Default initializer.
这就是为什么 EF 有时会为你做一些事情。
所以答案是“是的,您可以“创建无需迁移的数据库”
但区别并不明显,如果你愿意长期这样做则是另一个问题。
如果您正在使用迁移。它将更新数据库以匹配代码优先模型。
如果没有数据库,则意味着创建数据库。
这就是为什么自动迁移和 CreateDB 看起来很混乱,因为它们有时会导致相同的结果。但从技术上来说它们是不同的。
因此,通常仅使用代码优先自动“迁移”就足够了。
迁移可以是自动的,也可以是“托管的”。
托管迁移方法涉及生成代码、调整代码并运行 PM commandlet 或 POwershell 命令来实际执行迁移。
使用自动迁移,您只需设置初始化程序并访问 DBContext。
该过程分为两部分。
a) DB 初始化步骤。
在实例化 YourDBContext 之前立即执行此操作。
//eg
// DONT TOUCH MY DB or i break your back!
Database.SetInitializer(new ContextInitializerNone<YourDbContext>()); // Do Nothing,
// OR
// yes migrate my db to match my code please.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourDbContext, YourMigrationConfiguration>()); // Set to migration is requested, see config class below
使用迁移初始值设定项时指定的配置类如下所示
public class YourMigrationConfiguration<TContext> : DbMigrationsConfiguration<TContext>
where TContext : DbContext{
protected YourMigrationConfiguration() {
AutomaticMigrationsEnabled = true; // run it when needed. Do not wait for my PM Command
AutomaticMigrationDataLossAllowed = true; // if the new db look means dropping tables or columns go ahead and kill my data. So use this option with caution.
}
然后在需要时触发代码中的迁移。
Context.Database.Initialize(true); // i place this inside a method on my UoW class
首先编写 Db 初始化策略。 http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx
代码优先迁移推荐阅读 http://msdn.microsoft.com/en-us/data/jj591621
托管迁移 http://msdn.microsoft.com/en-us/data/jj554735
网络上有很多关于这个主题的文章。