简体   繁体   中英

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. 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. 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).

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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