问题描述
我有一个包含EF Core db上下文的类库项目。这是框架的一部分。
I have a class library project containing an EF Core db context. This is part of a framework.
我想扩展此上下文,但不对框架项目进行任何更改。第二个上下文将使用相同的数据库。
I want to extend this context but without making changes to the framework project. The second context would use the same database.
我在另一个类库中创建了另一个数据库上下文(类似于)。可以,我可以独立于其他上下文进行查询和创建迁移。
I created another db context in a different class library (something similar to this). This works ok, I can make queries and create migrations separately from the other context.
但是例如,如果我在第一个上下文中有一个User实体,在第二个上下文中有UserBooks ,当我尝试在两个上下文之间建立 join
时不起作用,出现异常
But for example if I have a User entity in the first context and UserBooks in the second, when I try to make a join
between the two contexts it doesn't work, getting exception
System.ArgumentNullException:值不能为null。
参数名称:entityType
这是已知的。
还尝试使用最新的NuGet软件包,但唯一的区别是错误消息更好
Also tried with latest NuGet package 3.0.0-preview3.19153.1 but the only difference is that the error message is better
不能在单个查询执行中使用多个DbContext实例。确保查询使用单个上下文实例
有什么方法可以
a。
或
b。扩展一个单独项目中的上下文,而不对主上下文进行任何更改(或进行最小更改)
b. extend a context in a separate project without making any (or minimal) changes to the 'main' context
推荐答案
两个db-context表示两个连接。您无法通过其他方式加入。
Two db-contexts means two connections. You can't join through different connections.
您可以将数据加载到程序中并在那里加入。请注意,这在大型数据集上很危险。
You can load you data to your program and join there. Be aware, that this is dangerous on big datasets.
var customers = new Ctx1().Customers.ToList(); // ToList() loads the data into your program
var orders = new Ctx2().Orders.ToList();
// Now we're not in the db anymore. We can do a simple List-Join:
customers.Join(orders, c => c.CustomerId, o => o.CustomerId, (c, o) => new { Customer = c, Order = o });
2。扩展现有的上下文
如果您要坚持一个连接,则只需扩展上下文即可。请注意,您正在以这种方式进行事务。
2. Extend your existing Context
If you want to stick to one connection you could simply extend your Context. Be aware that you're in one transaction this way.
public class FrameworkContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
public class ExtendedContext : FrameworkContext
{
public DbSet<Order> Orders { get; set; }
}
现在您可以加入:
var ctx = new ExtendedContext();
var myResult = ctx.customers.Join(ctx.orders, c => c.CustomerId, o => o.CustomerId, (c, o) => new { Customer = c, Order = o });
这篇关于跨多个项目或两个上下文之间的EntityFramework上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!