我有一个自定义的 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>());
}
总结一下,
可用的不同技术的正确用例是什么?
当我们将数据库从一个环境迁移到另一个环境时,迁移在所有条件下都能正常工作的理想策略是什么?
最佳答案
这是我对 Db Initializer
的尝试,它结合了 Migration
初始化程序和默认的 Db Create
初始化程序。 (注意:这并不理想,更像是一个简单的练习,但为您在这里提出的问题提供了解决方案,大部分都有效 - 只需检查我所做的所有更新)。
How to create initializer to create and migrate mysql database?
至于why
和how
- 要完全理解,我建议您也查阅 EF source code (这是新版本,但在很多方面都很相似)
1)
a) Db initializer 通常只被调用一次(每个连接)——当你第一次尝试访问你的“模型”时(第一次查询或类似的)。在您的初始化程序中放置一个断点以进行检查。
因此将它放在构造函数中是完全安全的(尽管我更喜欢在某个地方启动时使用它,也可以进行配置)。 它只在需要初始化时被调用(并且使用最后一组
),您不应该手动调用它。
无论如何,要强制执行初始化程序,您可以执行 this.Database.Initialize(force: true);
For when switching connections see my post on problems
Code first custom connection string and migrations without using IDbContextFactory
b) 如果您创建自己的 IDatabaseInitializer
并且您仍然希望迁移能够并行
您不应该只从外部调用 DbMigrator
- 因为您的自定义初始化程序会错过整个“数据库创建”(例如,如果您想要种子或其他东西 -检查我上面的例子)。
两者都是有效的“初始化器”——因此您需要将它们集成为一个,这会以某种方式链接
。请记住,执行顺序
很重要(请参阅上面的问题示例)- 您应该检查“空条件”,然后调用 DbMigrator
,然后进行您自己的初始化.我使用一个初始化器作为基类,并合并了另一个。
如果您只想种子
- 您可以使用迁移配置,如果合理的话,这是最简单的。
2)
非常“开放式”,没有单一的答案。通常它是有效的,但问题是 expexted...
迁移是 3 件事(如我所见)- 您的代码模型/实体、您的数据库/表以及 Db 中的
__MigrationHistory
系统表。所有 3 个都需要保持同步
。如果你“不同步”,你可以删除迁移表,重新创建迁移(带有一个标志来保留现有的数据库)然后像以前一样继续 - 即有实时数据的解决方案。为此,请参阅 How to ignore a table/class in EF 4.3 migrations ,移动数据库时,您需要删除/创建 Db 的权限,
确保您的连接正确(更改配置 - 并与您的 DbContext 名称或 ctor 同步),
保持简单,不要做花哨的事情或从代码切换连接(可能但有问题)等,
不要
混合数据库/代码
版本 - 即一个代码实体版本 - 一个数据库。如果您想与不同的代码版本(例如暂存、生产)共享同一个数据库 - 不要( Multi-Tenancy 解决方案将在 EF6 中可用 - 例如 this ),如果您需要手动应用数据库 - 通过
Update-Database
生成脚本
- 然后应用它,不要手动操作,否则您会弄错的(迁移历史表)- 参见 this one ,
...这只是少数几个。 IMO 非常稳定且可用 - 但如果您遵守规则 - 并且了解限制是什么。
class CreateAndMigrateDatabaseInitializer<TContext, TConfiguration>
: CreateDatabaseIfNotExists<TContext>, IDatabaseInitializer<TContext>
where TContext : DbContext
where TConfiguration : DbMigrationsConfiguration<TContext>, new()
{
private readonly DbMigrationsConfiguration _configuration;
public CreateAndMigrateDatabaseInitializer()
{
_configuration = new TConfiguration();
}
public CreateAndMigrateDatabaseInitializer(string connection)
{
Contract.Requires(!string.IsNullOrEmpty(connection), "connection");
_configuration = new TConfiguration
{
TargetDatabase = new DbConnectionInfo(connection)
};
}
void IDatabaseInitializer<TContext>.InitializeDatabase(TContext context)
{
var doseed = !context.Database.Exists();
// && new DatabaseTableChecker().AnyModelTableExists(context);
// check to see if to seed - we 'lack' the 'AnyModelTableExists'
// ...could be copied/done otherwise if needed...
var migrator = new DbMigrator(_configuration);
// if (doseed || !context.Database.CompatibleWithModel(false))
if (migrator.GetPendingMigrations().Any())
migrator.Update();
// move on with the 'CreateDatabaseIfNotExists' for the 'Seed'
base.InitializeDatabase(context);
if (doseed)
{
Seed(context);
context.SaveChanges();
}
}
protected override void Seed(TContext context)
{
}
}
关于c# - EF 中 IDatabaseInitializer 的正确用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15998931/