我有一个自定义的 DatabaseInitialiser,它在下面
/// <summary>
/// Implements the IDatabaseInitializer to provide a custom database initialisation for the context.
/// </summary>
/// <typeparam name="TContext">TContext is the DbContext</typeparam>
public class ParikshaDataBaseInitializer<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
/// <summary>
/// The method to Initialise the database.
/// Takes care of the database cannot be dropped since it is in use problem while dropping and recreating the database.
/// </summary>
/// <param name="context">The DbContext on which to run the initialiser</param>
public void InitializeDatabase(TContext context)
{
var exists = context.Database.Exists();
try
{
if (exists && context.Database.CompatibleWithModel(true))
{
// everything is good , we are done
return;
}
if (!exists)
{
context.Database.Create();
}
}
catch (Exception)
{
//Something is wrong , either we could not locate the metadata or the model is not compatible.
if (exists)
{
context.Database.ExecuteSqlCommand("ALTER DATABASE Pariksha SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
context.Database.ExecuteSqlCommand("USE Master DROP DATABASE Pariksha");
context.SaveChanges();
}
context.Database.Create();
}
}
}
关于上述代码的一些东西不仅仅是hacky(请随时提供帮助)
然后我添加了迁移并使迁移脚本也能正常工作。
internal sealed class Configuration : DbMigrationsConfiguration<ParikshaContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "EFRepository.Context.ParikshaContext";
}
protected override void Seed(ParikshaContext context)
{
}
}
迁移按预期工作。
现在,问题是在我的应用程序启动中我应该怎么做?像这样的东西
var config = new Configuration();
var migrator = new DbMigrator(config);
migrator.Update();
并且一些论坛也在构造函数中提出了这一点,这似乎有点奇怪,因为我不想在每次使用上下文时检查数据库和模式是否正确。那么,这种技术的可能用途是什么,或者我认为建议的上下文是错误的?
public ParikshaContext() : base("Pariksha")
{
Database.SetInitializer(new ParikshaDataBaseInitializer<ParikshaContext>());
}
总结一下,
可用的不同技术的正确用例是什么?
什么是理想的策略,以便迁移在所有条件下以及当我们将数据库从一个环境移动到另一个环境时工作?