如何优化LINQ查询?

时间:2018-08-25 09:47:48

标签: c# sql-server linq entity-framework-core

我编写了以下LINQ查询,以返回组列表,然后分别迭代列表。

我只需要带有特定电子邮件的用户组列表。

我确信这可能不会马上到来。

我可以用更好的方式(性能方面)重写它吗?

var groups = _context.Users.Where(m => m.Email == email)
                           .Include(g => g.Customer)
                           .ThenInclude(r => r.CustomerGroups)
                           .ThenInclude(t => t.Group)
                           .First().Customer.CustomerGroups;

foreach (var group in groups)
{
    var s = group.Group;
    //do something
}

2 个答案:

答案 0 :(得分:2)

尝试一下:

这是在CustomerGroups表上进行查询,因此您不需要包括CustomerCustomerGroups

var customerGroups = _context.CustomerGroups.Where(m => m.Customer.User.Email == email)
                    .Include(t => t.Group).
                     Select(s=> new CustomerGroupModel {
                           A= s.A,
                           B= s.B,
                           …
                           Group = s.Group
                     }).ToList();

  var customerGroups = _context.Customer.Where(m => m.User.Email == email)
                .Include(r => r.CustomerGroups).ThenInclude(t => t.Group).
                 Select(s=> new CustomerGroupModel {
                       A= s.CustomerGroups.A,
                       B= s.CustomerGroups.B,
                       …
                       Group = s.CustomerGroups.Group
                 }).ToList();

答案 1 :(得分:2)

如果您只需要带有相关 Group 实体的 CustomerGroup 实体(正如我在评论部分所解释的那样),则获取其他相关实体(用户客户)。您可以像这样使EF仅获取您感兴趣的实体:

var groups = 
(
    from user in _context.Users
    from customerGroup in user.Customer.CustomerGroups
    where user.Email == email
    select customerGroup
).Include(cg => cg.Group);

或者 CustomerGroup 不存储任何相关数据时,仅存储关系:

var groups = 
(
    from user in _context.Users
    from customerGroup in user.Customer.CustomerGroups
    where user.Email == email
    select customerGroup.Group
);