2013-06-05 51 views
0

我有這個LINQ查詢返回非靜態方法異常,因爲左連接有時會爲context.Betas返回一個空值。Linq:Non-static-methods-requires-a-target with select new {model}

return (from t in context.Alphas 
       join b in context.Betas on new { Id = t.Id } equals new { Id = b.AlphaId } into b_leftjoin 
       from b in b_leftjoin.DefaultIfEmpty() 
       where 
        t.UserProfileId == userProfileId 
        && t.IsClosed == false 
        && t.IsCancel == false 
        && t.EndDate <= DateTime.Now 
       orderby 
        t.Title 
       select new AlphaSelection() 
       { 
        Title = t.Title, 
        CurrentUser = b.UserProfile == null ? null : b.UserProfile, 
        BetaId = b.Id == null ? 0 : b.Id, 
        ProjectNumber = t.ProjectNumber, 
        AlphaId = t.Id 
       }).ToList(); 

如果我刪除CurrentUser和BetaId查詢工作,但我需要保留所有信息在一起。你能幫我解決這個問題嗎?

謝謝!


編輯(回答到評論):

實際的例外是這個:

非靜態方法需要一個目標。 描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。

Exception Details: System.Reflection.TargetException: Non-static method requires a target. 

Source Error: 


Line 39:    else 
Line 40:    { 
Line 41:     return query.ToList(); 
Line 42:    } 
Line 43:   } 
+1

什麼是**實際**異常? –

+0

你能給出例外的*確切的*細節嗎?目前還不清楚。 –

+0

'Id'的類型是什麼?你爲什麼使用'new {}'來進行連接? – Guvante

回答

4

您正在收到空引用異常。它被稱爲非靜態目標異常,因爲LINQ在後端使用反射來完成它的事情。

CurrentUser = b.UserProfile == null ? null : b.UserProfile, 
BetaId = b.Id == null ? 0 : b.Id, 

原因造成的,你需要做的

CurrentUser = b == null ? null : b.UserProfile, 
BetaId = b == null ? 0 : b.Id, 

由於引用類型的默認值爲null。

+0

或者你可以使用'??'而不是'whatever == null? defaultval:whatever' –

+0

真的很好!非常感謝你!! = D – Karine

+0

@newStackExchangeInstance:不是在這種情況下,他的原始格式是這種形式,但正確的版本不是,當最終結果使用「b」的一部分時,條件檢查'b'。 – Guvante