我有以下 LINQ 查询:
var query =
from store in _dbContext.Stores.AsNoTracking()
join shelf in _dbContext.Shelves.AsNoTracking()
on store.Id equals shelf.StoreId into storeShelf
join customers in
(
from customer in _dbContext.Customers.AsNoTracking()
where customer.IsActive
select new { customer.Name, customer.shelfId }
) on storeShelf.Id equals customers.shelfId into shelfCustomer
from shelfCustomer2 in shelfCustomer.DefaultIfEmpty()
select new CompleteModel
{
StoreName = store.Name,
CustomerName = shelfCustomer2.Name
};
问题是子查询翻译错误。而不是:
...
SELECT c.Name, c.Age
FROM [dbo].[Customer]
WHERE c.IsActive = 1
...
EF翻译为:
...
SELECT c.Id, c.Name, c.Surname, c.Age, c.AddressId, ...
FROM [dbo].[Customer]
WHERE c.IsActive = 1
在子查询中选择所有列,而不仅仅是这两个列。
即使 EF Core 3.x 已过时,它仍然应该正确处理以下 LINQ 查询:
var query =
from store in _dbContext.Stores
join shelf in _dbContext.Shelves on store.Id equals shelf.StoreId
from shelfCustomer in _dbContext.Customers
.Where(c => c.shelfId == shelf.Id && c.IsActive)
.DefaultIfEmpty()
select new CompleteModel
{
StoreName = store.Name,
CustomerName = shelfCustomer.Name
};
请注意,我已删除
AsNoTracking()
,因为它在使用投影时是多余的。此外,AsNoTracking()
只需在查询中应用一次。