文脉传承一个实体类型多个数据库上下文?
// MobileContext has VisitPlan, Customer, etc. that all the following contexts need.
public MobileContext : DbContext { }
public AuthenticationEntities : MobileContext { }
public OrderEntities : MobileContext { }
public ThriftEntities : MobileContext { }
的上下文是代码,第一,我不使用它们来创建数据库。
说明
我创造出具有存储库VisitPlan
,UserBranch
,等所有的库中的UserPermissionService
一个实例是在AuthenticationEntities
与Customer
和VisitPlan
是的MobileContext
这AuthenticationEntites
的一部分,其他情况从...继承。
问题
当我尝试执行联接查询UserBranch
和VisitPlan
它告诉我,我不能在两个上下文之间的查询,但如果我看在调试器在它们两者的库的DbContext
键入AuthenticationEntities
。
有没有办法做到这一点?
查询
//
// USER-BRANCHES: Check the user branches table for permissions.
//
var branches = Branches
.GetAll()
.Where(x => x.AzureUser.Username == username && x.StartDate <= effective && x.EndDate >= effective);
//
// USER-ROUTES: Check the user routes table for permissions.
//
var routes = Routes
.GetAll()
.Where(x => x.AzureUser.Username == username && x.StartDate <= effective && x.EndDate >= effective);
//
// USER-DRIVERS: Check the user driver number table for permissions.
//
var drivers = DriverNumbers
.GetAll()
.Where(x => x.AzureUser.Username == username && x.StartDate <= effective && x.EndDate >= effective);
//
// VISIT PLANS: Retrieve a list of visit plans currently active.
//
var vpQuery = VisitPlans
.GetAll()
.Where(
x => x.FromDate <= effective && x.ToDate >= effective
&& (
branches.Any(b => b.Branch == x.Branch)
|| routes.Any(r => r.Route == x.Route)
|| drivers.Any(d => d.DriverNumber == x.DriverNumber)
)
);
//
// QUERY: Retrieve all the customers which have effective stop plans and are included in one of the above queries.
//
var customerQuery = vpQuery
.Join(
inner: Customers.GetAll(),
outerKeySelector: x => x.SAPCustomerID,
innerKeySelector: x => x.SAPCustomerID,
resultSelector: (vp, c) => c
);
其中:
VisitPlans
是Repository<VisitPlan>
类型其使用AuthenticationEntities
作为其DbContext
Customers
的是类型的10,它使用AuthenticationEntities
作为其DbContext
Branches
是Repository<UserBranch>
型其使用AuthenticationEntities
作为其DbContext
Routes
的是Repository<UserRoute>
类型其使用AuthenticationEntities
作为其DbContext
DriverNumbers
被Repository<UserDriverNumber>
类型其使用AuthenticationEntities
的作为它的DbContext
请分享您的查询码。您应该有一个负责查询的DbContext实例,以及从该查询返回的所有实体。你不能连接不同的'DbContext'实例(*我也不知道你为什么想要*)。 – Igor
如果我添加查询代码,它将需要一堆其他代码,页面将长达一英里。查询不是问题,问题是我在所有上下文中都有一些实体(即VisitPlan等),当我在一个特定上下文(例如UserBranch,UserRoute等)的实体和实体之间加入时,它抱怨两个上下文,即使这些存储库正在使用“AuthenticationEntities”的实例。所以对我来说,似乎有一个与'VisitPlan'和其他实体在多个上下文的问题,这就是我所问。 – Shelby115
@ Shelby115这听起来像你需要重新考虑你的设计。除非有特殊情况,例如拥有多个数据库,否则您应该只有一个上下文。如果您正在使用存储库模式(实体框架不需要这种模式),则应该在需要时注入上下文。 – JNYRanger