EF Query:如何将零计数子查询转换为null

时间:2013-07-06 15:56:05

标签: c# linq entity-framework

使用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.IQueryable`1'的null常量值! 我想知道为什么Entity Framework将此查询转换为T-SQL非常困难。检查子查询并在结果计数为零时返回NULL似乎并不那么复杂。

非常感谢任何解决方案和解释。

1 个答案:

答案 0 :(得分:2)

解决方案是 IQueryable.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
             };