2013-02-10 66 views
1
 var query = 
      (from Contact con in e.Results 
      from ContactPhoneNumber phn in con.PhoneNumbers 
      from ContactEmailAddress email in con.EmailAddresses.DefaultIfEmpty() 
      where con.DisplayName.Contains(txtContasctSearch.Text) 
      select new person() 
      { 
       displayName = con.DisplayName, 
       displayEmail = (email.EmailAddress == null ? String.Empty : email.EmailAddress), 
       displayPhone = phn.PhoneNumber 
      }).ToList(); 

EmailAddress字段並不總是可用。但是,如果存在,我仍然希望將其還原。我想模仿一個左連接,但是,上面的代碼返回一個錯誤。Linq with LEFT加入

任何想法?

我收到的錯誤是:

System.NullReferenceException occurred 
    _HResult=-2147467261 
    _message=NullReferenceException 
    HResult=-2147467261 
    Message=NullReferenceException 
    Source=wpChoreList 
    StackTrace: 
     at wpChoreList.personSetup.<Contacts_SearchCompleted>b__8(<>f__AnonymousType1`2 h__TransparentIdentifier1) 
    InnerException: 
+3

_What沒有錯誤說_ – SLaks 2013-02-10 14:33:47

+0

我建議你先看看這個問題 - HTTP:// stackoverf low.com/questions/700523/linq-to-sql-left-outer-join – 2013-02-10 14:34:32

回答

2

您要爲空檢查錯誤值:

displayEmail = (email.EmailAddress == null ? String.Empty : email.EmailAddress), 

電子郵件應該是空的,沒有email.EmailAddress,請嘗試更改該行本之一:

displayEmail = (email == null ? String.Empty : email.EmailAddress), 
+0

就是這樣!當這樣簡單的事情...謝謝。只要它允許我,我會盡快答覆。 – webdad3 2013-02-10 14:41:06