2013-07-06 58 views
0

使用EF 4.5,我想一個零計數子查詢(relatedDrivers)轉換爲空在下面的語句:EF查詢:如何轉換零計數子查詢爲空

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'類型的空常量值! 我想知道爲什麼這對於Entity Framework將此查詢轉換爲T-SQL非常困難。如果結果數爲零,則檢查子查詢並返回NULL似乎並不那麼複雜。

任何解決方案和解釋是高度讚賞。

+0

爲什麼你需要它爲空,而不是空列表 – MEYWD

+0

將查詢傳遞如果去掉零檢查? –

+0

我有點生疏,你不應該由CarID分組來計算每輛車的司機數嗎? – Alexandre

回答

2

解決方案是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 
      };