如何在Entity Framework Core中加载对象图?

时间:2017-11-02 22:02:48

标签: linq entity-framework-core

我有一些我需要获取的关系数据

from user in Users
  .Include("UserCategoryPermissions")
  .Include("UserResourcePermissions")
  .Include("UserPermissions.Permission.Application")
  .Include("UserGroupMembers.UserGroup.UserGroupPermissions.Permission.Application")
where user.Id == 3

Entity Framework Core通过执行多个查询来获取此数据。我想要做的就是将一个对象图加载到内存中(没有投影),多次查询会让事情变慢。

我可以通过执行包含大量连接的大量查询来预加载这些对象

from a in A
join b in B on a.Id equals b.A_Id into bJoin from b in bJoin.DefaultIfEmpty()
join c in C on b.Id equals c.B_Id into cJoin from c in cJoin.DefaultIfEmpty()
join x in X on a.Id equals x.A_Id into xJoin from x in xJoin.DefaultIfEmpty()
// etc
select new {
  a, b, c, x
}

但每次我想要获取数据时都必须这样做,这将是一个真正的痛苦。有没有办法让Entity Framework Core预先加载数据图?理想情况下,我希望它能够从一个字符串数组中工作,其中每个字符串都标识一个路径(如上所述),但我很乐意了解这些图形可以通过参数传递给方法的任何方式。< / p>

1 个答案:

答案 0 :(得分:1)

我通常使用lambda语法,它在一次调用中获取所有数据:

using System.Linq;
using Microsoft.EntityFrameworkCore;
...

var userFound = context.Users
    .Include(user => user.UserCategoryPermissions)
    .Include(user => user.UserResourcePermissions)
    .Include(user => user.UserPermissions)
    .ThenInclude(map => map.Permission)
    .ThenInclude(permission => permission.Application)
    .Include(user => user.UserGroupMembers)
    .ThenInclude(members => members.UserGroup)
    .ThenInclude(group => group.UserGroupPermissions)
    .ThenInclude(map => map.Permissions)
    .ThenInclude(permission => permission.Application)
    .Where(user => user.Id == 3);

请注意,IncludeThenInclude intellisense的lambda内部无法正常工作。只需盲目输入正确的属性名称即可。