简体   繁体   中英

How I can optimize my LINQ query?

I have written following LINQ query to return list of Groups and then iterating list separately.

I only need list of Groups of User with specific email.

I am sure this might not be the right away.

Can i re-write it in a better way (performance-wise) ?

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
}

Try this :

That is make query on CustomerGroups table so You don't need Include Customer and CustomerGroups .

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

Or

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

If you need just CustomerGroup entities with the related Group entity (as I interpret your clarification in the comment section) it's inefficient to fetch other related entities ( User and Customer ). You can make EF to fetch only the entities you are interested in like this:

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

Or when CustomerGroup stores no relevant data, just relationships:

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

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