2011-09-07 65 views
1

我有以下代碼:問題與對象Where子句

IList<CmsUserPermissionGroup> matchingRoles = PermissionGroups.Where(r => r.JournalCode.ToLower() == journalCode.ToLower()) 
                   .Where(r => r.CmsRole.ToLower() == role.ToLower()) 
                   .Where(r => r.AccessLevel > 0) 

,我認爲,如果不返回任何結果將返回一個空列表。實際返回的是以下錯誤:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

我誤解了什麼嗎?還有什麼其他的選擇?

+1

您確定NullReferenceException沒有被生成,因爲您正在調用ToLower()實例的某個屬性爲null? –

+0

似乎是這種情況,正如在下面的答案中已經強調的那樣 - 感謝您的意見。 – MichaelS

回答

3

如果查詢沒有問題,則返回空的枚舉。

這裏的問題是在你的Where()聲明中。 JournalCodeCmsRole爲空(假設您已在PermissionGroups的其中一個對象上檢查了journalCoderole其他位置的空值)。當您在該值上調用ToLower()時,它會拋出上述異常。

你可以更好一點保護自己以下:

if(!String.IsNullOrEmpty(journalCode) && !String.IsNullOrEmpty(role)) 
{ 
    Roles = 
     PermissionGroups 
      .Where(r => r.JournalCode != null 
         && r.JournalCode.Equals(journalCode, 
          StringComparison.InvariantCultureIgnoreCase)) 
      .Where(r => r.CmsRole != null 
         && r.CmsRole.Equals(role, 
          StringComparison.InvariantCultureIgnoreCase)) 
      .Where(r => r.AccessLevel > 0); 
} 
+0

或者你可以使用* String.Equals(journalCode,r.JournalCode,StringComparison.InvariantCultureIgnoreCase); *這將自動防止兩個字符串爲空 - 如果兩者都爲null,將返回true(有用的,如果這是你想要的發生!) –

2

,如果不返回任何結果和謂詞成功返回一個空序列。

當它發生時,它看起來像任何r是空的一些元素,或r.JournalCode是空的一些元素,或journalCode爲空,或者r.CmsRole爲空對某些元素,或role爲空。 LINQ不會阻止這些異常冒泡。

+0

那麼,我們如何防止這些異常冒泡?我有類似的案例發佈[這裏](http://stackoverflow.com/q/39382660/1232087)當t.price在LEFT OUTER連接中爲空時,t.price引發這個異常(當連接條件不符合) – nam

+0

@nam:檢測並處理它 - 如果它可能爲空,不要解除引用t ... –