简体   繁体   English

来自相关实体的EF Eager负载相关实体

[英]EF Eager load related entities from related entity

I'm having difficulties with eagerly loading a complex relation type. 我在急于加载复杂的关系类型时遇到困难。 Consider my entities: 考虑我的实体:

public class User
{
    public string UserName { get; set; }
}

public class Ownership
{
    public User   Owner  { get; set; }
    public Device Device { get; set; }
}

public class Device
{
    public License License { get; set; }
}

Assume that all entities are in separate tables. 假定所有实体都在单独的表中。 I left out all the non-essential convention code. 我忽略了所有不必要的约定代码。 I can post more when needed. 我可以在需要时发布更多信息。

My query: 我的查询:

var result = return context.Ownerships
              .Include(o => o.Device.License)
              .Where(o => o.Owner.UserName == userName)
              .Select(o => o.Device).ToList();

But this results in null valued licenses for all devices. 但这会导致所有设备的许可证null However if I define the License like this: 但是,如果我这样定义许可证:

public class Device
{
    public virtual License License { get; set; }
}

And query like this: 并像这样查询:

var result = return context.Ownerships
              .Where(o => o.Owner.UserName == userName)
              .Select(o => o.Device).ToList();

It works (License is not null for devices) but I rather not lazy load by default. 它可以工作(设备的许可证不是null ),但默认情况下我不是延迟加载。 The entities are served over rest so, by serialization, I get license info for each device that I query which is a lot of data over the line I don't need. 这些实体可以为其余人员提供服务,因此,通过序列化,我可以获得所查询的每台设备的许可证信息,这是我不需要的大量数据。

Any hints? 有什么提示吗?

Solution

var result = return context.Ownerships
    .Where(o => o.Owner.UserName == userName)
    .Select(o => o.Device)
        .Include(d => d.License)
        .ToList();

Include only works on the projection of the thing you are doing it on. 仅包括对您正在做的事情的投影的作品。

In your case you are defining includes on Ownership but projecting Device which doesn't have any includes defined on it (eg .Include(o => o.Device.License) doesn't count). 在您的情况下,您正在定义Ownership包含,但是在投影Device上没有定义任何包含(例如, .Include(o => o.Device.License)不计在内)。

You might be able to do this (but I haven't tested it): 您可能可以执行此操作(但我尚未对其进行测试):

return context.Ownerships
          .Where(o => o.Owner.UserName == userName)
          .Select(o => o.Device)
          .Include(d=>d.License)
          .ToList();

if not reverse the way you are querying eg: 如果没有扭转您查询的方式,例如:

return context.Devices
          .Include(d => d.License)
          .Where(d => d.Ownerships.Any(o=>o.Owner.UserName == userName))
          .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM