1

使用 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”的空常量值!我想知道为什么实体框架很难将此查询转换为 T-SQL。如果结果计数为零,则检查子查询并返回 NULL 似乎并没有那么复杂。

任何解决方案和解释都受到高度赞赏。

4

1 回答 1

3

解决方案是IQueriable.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
             }; 
于 2013-07-07T13:33:43.697 回答