gpt4 book ai didi

entity-framework-5 - 如果它改变了代码的行为,那么添加一个继承自某些东西的类是否违反了可靠的原则?

转载 作者:行者123 更新时间:2023-12-04 05:03:15 24 4
gpt4 key购买 nike

我努力使我的代码能够使用不同的连接字符串运行代码优先的 EF 迁移,最后让它工作。

我在对 this question 的回答中概述了我使用的方法。

困扰我的是,为了能够使用不同的连接字符串运行相同的代码,我必须

1)采用全局设置来存储连接字符串

2) 引入一个类,它的存在导致代码行为不同。

这与我习惯的工作方式大不相同。这里使用的技术是否违反了坚实的原则?有没有其他不违反原则的方法?

更新:
概述了一种不同的方法 - 可能更明智 here

最佳答案

(all this is is related to what's in here How does Database.SetInitializer actually work? (EF code-first create database and apply migrations using several connection strings) - but was getting into entirely different direction - so I think it makes sense to be separated. Read there before this)



更新:

这里变得有趣了。 我确实设法重现了您实际面临的问题 .以下是我认为正在发生的事情的简短分割:

首先,这很“高兴”:
Database.SetInitializer(new CreateAndMigrateDatabaseInitializer<MyContext, MyProject.Migrations.Configuration>());
for (var flip = false; true; flip = !flip)
{
using (var db = new MyContext(flip ? "Name=MyContext" : "Name=OtherContext"))
{
// insert some records...
db.SaveChanges();
}
}

(我使用了自定义初始化程序 from my other post ,它一起控制迁移/创建过程)

在没有初始化程序的情况下效果很好。一旦我打开它,我就遇到了一些奇怪的问题。

我删除了 Db-s(每个连接两个)。我希望要么不工作,要么创建一个数据库,然后在下一次传递中创建另一个(就像它所做的那样,没有迁移,只是“创建”初始值设定项)。

What happened, to my surprise - is it actually created both databases on the first pass ??



然后,作为一个好奇的人:),我在 MyContext 上设置了断点ctor,并通过迁移器/初始化程序进行调试。再次为空/没有 db-s 等。

它在我的调用中创建了第一个实例 flip .然后在第一次访问“模型”时,它调用了初始化程序。 Migrator 接管了(没有 db-s)。期间 migrator.Update();它实际上构造了 MyContext (我猜测通过配置中的通用参数) - 并调用“默认”空构造函数。默认情况下具有“其他连接/名称” - 并且也创建了其他 Db。

所以,我认为这解释了你正在经历的事情。以及为什么您必须创建“工厂”来支持上下文创建。这似乎是唯一的方法。并设置一些“AppDomain”宽的“连接字符串”(实际上您确实发现了它),它不会被空的 ctor 调用“覆盖”。

我看到的解决方案是 - 你只需要通过工厂运行所有东西 - 并在那里“翻转”连接(不需要静态连接,只要你的工厂是单例。

This actually doesn't work at all (my test at least) with an official MigrateDatabaseToLatestVersion initializer - and the reason why I used the other one.

关于entity-framework-5 - 如果它改变了代码的行为,那么添加一个继承自某些东西的类是否违反了可靠的原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15856703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com