简体   繁体   中英

LINQ OrderBy for complex entity

I have complex query:

var containers = this.Repository.Containers
                .Include(x => x.PostsContainers)
                .ThenInclude(x => x.Post)
                .ThenInclude(x => x.TasksPosts)
                .ThenInclude(x => x.Task)
                .ThenInclude(x => x.AssignedToUser);

var items = containers.Where(x => x.PostsContainers
                              .Any(y => y.Post.TasksPosts
                                  .Any(z => z.Task.DateDue <= DateTime.UtcNow.AddDays(7)
                                      && !z.Task.Completed
                                      && z.Task.AssignedToUserId.Value == userId)));

I got items but I also need to sort these items by Task.DueDate and extract AssignedToUser name.

What's the best way to do it (with good performance, without code duplication)? Maybe I need to rewrite my code?

Try to refactor it this way:

  var dateDue = DateTime.UtcNow.AddDays(7)

  var result = (from c in this.Repository.Containers
                from pc in c.PostsContainers
                from tp in pc.Post.TasksPosts
                where tp.Task.DateDue <= dateDue
                   && !tp.Task.Completed
                   && tp.Task.AssignedToUserId == userId
                orderby tp.Task.DueDate
                select new
                {
                    Container = c,
                    tp.Task.AssignedToUser
                })
                .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