EF表每类型带子属性表的导航属性 [英] EF Table Per Type with Navigation property on Sub Type Table
问题描述
简化背景:
我正在使用实体框架V1构建我的类结构,如下所示,我使用Table Per Type来保存我的继承对象:
Employee
CaseA:案例
案例B:案例
案例分析:案例
CaseB有一个Navigational属性to Employee
我有一个Repository返回一个ObjectQuery。如果Case的类型实际上是CaseB,我需要在图中包含Employee对象。我不能.Include(Employee),因为它不是Case的导航属性,而Employee没有.Load()方法。
理想情况下,我希望能够在一个查询中执行此操作,但是由于回调我很高兴我打电话,检查对象并执行另一个调用,如下所示:(尽管如前所述,load doesn'存在于员工导航资源上)
//从
获取案例case myCase = new Repo< Case ,Entities> .FirstOrDefault();
if(myCase是CaseB)
((CaseB)myCase).Employees.load();
我在这里缺少一些非常简单的东西?
尝试这样:
var employee = ctx.Cases
。 OfType< CaseB>()
.Include(Employees)
.Select(x => x.Employees)
.FirstOrDefault();
OfType< T>()
在EF中最重要的方法是继承 - 你应该熟悉它。
本质上是将查询中的项目过滤为特定类型 - 非常类似于您在答案中的条件检查。
这是一个 IQueryable
方法(LINQ-Objects),但在LINQ实体( ObjectQuery< T>
),它被实现为INNER JOIN。
上述应该可以正常工作 - em> after 后,您可以执行 OfType
。
HTH。
I'm hoping someone out in the SO community will be able to help me out here.
Simplified Background: I'm using Entity Framework V1 to build my class structure that is outlined below, I'm using Table Per Type to persist my inherited objects:
Employee
CaseA : Case
CaseB : Case
CaseC : Case
CaseB has a Navigational Property to Employee
I have a Repository that returns an ObjectQuery. If the type of Case is actually CaseB, I need to include the Employee object within the graph. I can't .Include("Employee") because it's not a navigational property of Case, and Employee doesn't have a .Load() method on it.
Ideally I want to be able to do this in one query, however as a fall back I'm happy that I make a call, check the Object and perform another call, something like this: (although as I stated earlier, load doesn't exist on the employee navigational property)
//Get the case from the
Case myCase = new Repo<Case, Entities>.FirstOrDefault();
if(myCase is CaseB)
((CaseB)myCase).Employees.load();
Am I missing something really simple here?
Try this:
var employee = ctx.Cases
.OfType<CaseB>()
.Include("Employees")
.Select(x => x.Employees)
.FirstOrDefault();
OfType<T>()
is one of the most important methods in EF when it comes to inheritance - you should familiarize yourself with it.
Essentially is filters the items in the query to be of a particular type - very similar to the conditional check your doing in your answer.
It's an IQueryable
method (LINQ-Objects), but in LINQ-Entities (ObjectQuery<T>
), it get's implemented as an INNER JOIN.
The above should work - just make sure you do the eager load after you do the OfType
.
HTH.
这篇关于EF表每类型带子属性表的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!