EF查询:如何将零计数子查询转换为空
本文关键字:查询 转换 EF | 更新日期: 2023-09-27 18:21:13
使用EF 4.5,我想在以下语句中将零计数子查询(relatedDrivers)转换为null:
var query = from car in context.tblCar
let relatedDrivers = (from driver in context.tblDriver
where driver.CarId == car.CarId
select driver)
select new
{
CarId = car.CarId,
Drivers = relatedDrivers.Count() == 0 ? null : relatedDrivers
};
但我得到了"NotSupportedException",它指出不可能创建类型为"System.Linq.IQUERABLE`1'"的null常数值!我想知道为什么实体框架很难将这个查询转换为T-SQL。检查子查询并在结果计数为零时返回NULL似乎并不那么复杂。
非常感谢任何解决方案和解释。
解决方案是IQuerable.DefaultIfEmpty()。因此查询将更改为:
var query = from car in context.tblCar
let relatedDrivers = (from driver in context.tblDriver
where driver.CarId == car.CarId
select driver).DefaultIfEmpty()
select new
{
CarId = car.CarId,
Drivers = relatedDrivers
};