实体框架:继承和包含 [英] Entity Framework: Inheritance and Include

查看:90
本文介绍了实体框架:继承和包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下层次结构:

class Department { EntityCollection<Employee> Employees; }

class Employee { string Name; }

class RemoteEmployee : Employee { Country Location; EntityReference<Country> CountryReference; }

所以,部门包含员工列表。有一个员工类型的层次结构,一些类型引用其他实体。我们假设我们需要向员工加载部门。确定,不是问题:

So, department contains a list of employees. There is a hierarchy of employee types, some types reference other entities. Let's suppose we need to load department with its employees. OK, not a problem:

dataContext.Departments.Include("Employees")

这将返回具体的员工类型(即RemoteEmployee for Remote)。
现在我们需要加载远程员工的位置。

This returns concrete employee types (i.e. RemoteEmployee for Remote ones). Now we need to load Location with Remote employees.

dataContext.Departments.Include("Employees").Include("Employees.Location") - Error: no such property in Employee
dataContext.Departments.Include("Employees").Include("RemoteEmployees.Location") - Error: no such property in Department

我要在Include中指定加载位置与RemoteEmployee?

What should I specify in Include to load Location with RemoteEmployee?

推荐答案

我很确定CatZ建议不行。

I'm pretty sure what CatZ suggests doesn't work.

我不认为你可以这样做包括,但您可以使用投影技巧实现相同的效果,请参阅此如何排序实体框架中的关系

I don't think you can do this using Include, but you can achieve the same effect using a projection trick see this How to Sort Relationships in the Entity Framework

您需要做的是这样的: / p>

What you need to do is something like this:

var results = from d in ctx.Departments
              select new {
                   d, 
                   employees = d.Employees.Select(
                      e => new {
                          e, 
                          location = e is RemoteEmployee ? 
                                     (e as RemoteEmployee).Location : 
                                     null
                     }
                   )
              };


foreach (var result in results)
{
    var re = result.d.Employees.First() as RemoteEmployee;
    Console.WriteLine("{0} {1} works from {2}", 
           re.Firstname, re.Surname, re.Location.Name);
}

请注意,您不需要使用匿名类型来获取数据基本上做这个投影有一个副作用是填充你的部门的收藏,因为实体框架的一个功能叫做fixup。

Notice that you don't need to use the anonymous types to get the data, essentially doing the projection has a side-effect of filling the collections on you department because of a feature of the Entity Framework called fixup.

希望这有助于
Alex

Hope this helps Alex

这篇关于实体框架:继承和包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆