Linq select distinct count performed in memory

こ雲淡風輕ζ 提交于 2019-12-05 12:30:34

The query is executing in memory because you instantiating a collection of BookListViewModel objects with the statement

.Select(i => new BookListViewModel
            {...})

If you simply remove the class BookListViewModel, Linq will execute the perform the query on the db side (which is a good idea since the optimizer is much more efficient) like this...

.Select(i => new
            {
                Count = i.Select(orders => orders.OrdererId).Distinct().Count(s => s != null),
                i.Key.OrganizationId,
                i.Key.BooklistName,
                i.Key.LocationName,
                i.Key.BooklistId,
                i.Key.Group1,
                i.Key.Group2,
                i.Key.Group3,
                i.Key.DepartmentId,
                ExpectedDate = i.Max(orders => orders.ExpectedDate)
            })

Then you can instantiate your collection at the end so the whole thing will look like this...

await _context
            .Orders
            .Where(i => i.DepartmentId != null && i.DepartmentId.Equals(Parameters.DepartmentId))
            .Where(i => i.SchoolYear.Equals(Parameters.SchoolYear))
            // Group the data.
            .GroupBy(orders => new
            {
                orders.BooklistId,
                orders.BooklistName,
                orders.OrganizationId,
                orders.DepartmentId,
                orders.LocationName,
                orders.Group1,
                orders.Group2,
                orders.Group3
            })
            .OrderBy(i => i.Key.BooklistName)
.Select(i => new
            {
                Count = i.Select(orders => orders.OrdererId).Distinct().Count(s => s != null),
                i.Key.OrganizationId,
                i.Key.BooklistName,
                i.Key.LocationName,
                i.Key.BooklistId,
                i.Key.Group1,
                i.Key.Group2,
                i.Key.Group3,
                i.Key.DepartmentId,
                ExpectedDate = i.Max(orders => orders.ExpectedDate)
            })
            .Select(i => new BookListViewModel
            {
                Count = i.Count,
                Id = i.Id,
                Name = i.Name,
                LocationName = i.LocationName,
                Number = i.Number ,
                Group1 = i.Group1 ,
                Group2 = i.Group2,
                Group3 = i.Group3,
                DepartmentId = i.DepartmentId,
                ExpectedDate = i.ExpectedDate
            })
            .ToListAsync();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!