[英]Errors using DefaultIfEmpty() in LINQ query with group by
我有以下 LINQ (to SQL Server) 查询:
var railcarsByProduct = await (from r in DbContext.Railcars
let p = DbContext.ProductAliases
.Where(pa => pa.Product.Company.CompanyCode == companyCode && pa.Alias == r.Product)
.Select(pa => pa.Product.Name)
.FirstOrDefault()
where r.Facility.Company.CompanyCode == companyCode && r.Departure == null
group r by p into productGroup
select new { Product = productGroup.Key, Count = productGroup.Count() }
).ToListAsync();
这工作正常。 但是, ProductAliases
子查询有可能返回 null。 在这种情况下,我想默认为r.Product
。
我尝试将DefaultIfEmpty()
添加到子查询中。
var railcarsByProduct = await (from r in DbContext.Railcars
let p = DbContext.ProductAliases
.Where(pa => pa.Product.Company.CompanyCode == companyCode && pa.Alias == r.Product)
.Select(pa => pa.Product.Name)
.DefaultIfEmpty(r.Product)
.FirstOrDefault()
where r.Facility.Company.CompanyCode == companyCode && r.Departure == null
group r by p into productGroup
select new { Product = productGroup.Key, Count = productGroup.Count() }
).ToListAsync();
但这给出了一个错误。
'LINQ 表达式 'DbSet() .Where(pa => pa.Product.Company.CompanyCode == __companyCode_0 && pa.Alias == r.Outer.Outer.Product) .Select(pa => pa.Product.Name) .DefaultIfEmpty(r.Outer.Outer.Product)' 无法翻译。 以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估。
接下来,我尝试在group by
子句中处理 null 情况。
var railcarsByProduct = await (from r in DbContext.Railcars
let p = DbContext.ProductAliases
.Where(pa => pa.Product.Company.CompanyCode == companyCode && pa.Alias == r.Product)
.Select(pa => pa.Product.Name)
.FirstOrDefault()
where r.Facility.Company.CompanyCode == companyCode && r.Departure == null
group r by p ?? r.Product into productGroup
select new { Product = productGroup.Key, Count = productGroup.Count() }
).ToListAsync();
但这也给出了完全相同的错误。
我知道可以只删除所有行,然后将它们分组到 C# 代码中。 但是有没有人看到我不需要这样做的方式?
尝试使用类似下面的东西。
var railcarsByProduct = await (from r in DbContext.Railcars
let p = DbContext.ProductAliases
.Where(pa => pa.Product.Company.CompanyCode == companyCode && pa.Alias == r.Product)
.Select(pa => pa.Product.Name)
.FirstOrDefault() ?? r.Product
where r.Facility.Company.CompanyCode == companyCode && r.Departure == null
group r by p into productGroup
select new { Product = productGroup.Key, Count = productGroup.Count() }
).ToListAsync();
不确定它是否会起作用,但我知道 DefaultIfEmpty 很奇怪,或者过去对实体框架很奇怪。
尝试以下查询:
var query =
from r in DbContext.Railcars
from p in DbContext.ProductAliases
.Where(pa => pa.Product.Company.CompanyCode == companyCode && pa.Alias == r.Product)
.Select(pa => pa.Product.Name)
.Take(1)
.DefaultIfEmpty()
where r.Facility.Company.CompanyCode == companyCode && r.Departure == null
group r by p ?? r.Product into productGroup
select new
{
Product = productGroup.Key,
Count = productGroup.Count()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.