2012-08-10 96 views
0

我從下面的左外得到一個對象引用問題加入LINQ查詢:對象問題

result.Data = from c in resourceActions.Actions 
         join o in roleResourceActions.Actions on c.ActionID equals o.ActionID into g 
         from a in g.DefaultIfEmpty() 
       select new 
       { 
        ActionID=c.ActionID, 
        ActionName=c.ActionName 
        ,IsSelected = a.ActionName==null?false:true 
       }; 

當我追查上述LINQ查詢,似乎對象「A」本身就是空。但是,基於此對象的只有我可以得到價值「IsSelected」

回答

1
result.Data = from c in resourceActions.Actions 
         join o in roleResourceActions.Actions on c.ActionID equals o.ActionID into g 
         from a in g.DefaultIfEmpty() 
       select new 
       { 
        ActionID=c.ActionID, 
        ActionName=c.ActionName 
        ,IsSelected = a != null && a.ActionName==null ? false : true 
       }; 
2

如果你希望a是在某些查詢無效,你可以測試之前閱讀ActionName

result.Data = from c in resourceActions.Actions 
        join o in roleResourceActions.Actions on c.ActionID equals o.ActionID into g 
       from a in g.DefaultIfEmpty() 
       select new 
       { 
        ActionID=c.ActionID, 
        ActionName=c.ActionName, 
        IsSelected = a != null && a.ActionName != null 
       }; 
0

你重新呼叫DefaultIfEmpty,這將返回您調用它的查詢類型的default值。

由於查詢的類型是參考類型,因此DefaultIfEmpty返回null

所以解決方案取決於您是否希望您的查詢返回元素,如果您的join產生元素或不。

如果不是,只是將其刪除:

result.Data = from c in resourceActions.Actions 
       join o in roleResourceActions.Actions on c.ActionID equals o.ActionID into g 
       from a in g 
       select new 
       { 
       ActionID=c.ActionID, 
       ActionName=c.ActionName, 
       IsSelected = a.ActionName==null?false:true 
       };