[英]entity framework DDD
I work on a EF Core project for WPF app. 我正在为WPF应用程序进行EF Core项目。 We decide to split the DbContext in 2 smallers : (the project contains a single Database) 我们决定将DbContext分成两个较小的部分:(该项目包含一个数据库)
public class FirstDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DBSet<Parameters>{ get; set; }
}
public class SecondDbContext: DbContext
{
public DBSet<User>{ get; set; }
public DBSet<Books> { get; set; }
public DBSet<Parameters>{ get; set; }
}
and we keep a "super" DbContext (wich contains all the DbSets from the DB) to maintain and migrate the DB 并且我们保留一个“超级” DbContext(其中包含来自数据库的所有DbSet)来维护和迁移数据库
public class SuperDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DBSet<User>{ get; set; }
public DBSet<Books> { get; set; }
public DBSet<Parameters>{ get; set; }
}....
The first step to refactore code is to replace the lines wich references the "SuperDbContext..." with the correct call "SecondDbContext.Books..."or "FirstDbContext.Post"... OK 重构代码的第一步是用正确的调用“ SecondDbContext.Books ...”或“ FirstDbContext.Post”替换引用“ SuperDbContext ...”的行...确定
Question : In the Client app, the choice of DbContext is depending about a user's choice when app is launching : if user choose option1 => FirstDbContext, and if option2 => SecondDbContext. 问题:在客户端应用程序中,DbContext的选择取决于应用程序启动时用户的选择:如果用户选择option1 => FirstDbContext,以及option2 => SecondDbContext。
How can we write the code to switch on the current DbContext to manage the "common DbSet" (Parameters) : before refactoring we have for example : SuperDbContext.Parameters.FirstOrDefault()... and now ? 我们如何编写代码以打开当前DbContext来管理“公共DbSet”(参数):在重构之前,我们有例如:SuperDbContext.Parameters.FirstOrDefault()...现在? do we have to write something like this : 我们必须写这样的东西吗:
if(option1)
{
FirstDbContext.Parameters.First()
}else
{
SecondDbContext.Parameters.First()
}
And what is the impact in the repositories ? 对存储库有什么影响? cause if we maintain this approach we have to duplicate code in the 2 Repositories :-( ? 因为如果我们保持这种方法,我们必须在2个存储库中重复代码:-(?
No no... Forget about the approach you mentioned, you'll end up writing twice the code you need. 不,不...忘记您提到的方法,您将最终编写所需代码的两倍。 Why don't you just use db context type : 您为什么不只使用db上下文类型:
At the beginning of your function, a single if else
: 在函数开始时, if else
,则使用一个:
DbContext context;
if(option1)
{
context = new firstContextEntities();
}
else
{
context = new secondContextEntities();
}
And as both of your contexts are almost exactly the same, you will use your context by casting it to the greater one (the one that has the most access) : 并且由于您的两个上下文几乎完全相同,因此您可以通过将上下文转换为更大的上下文(访问最多的那个上下文)来使用它:
var FirstLine = ((secondContextEntities)context).Parameters.First();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.