2011-01-27 108 views
0

當我用下面的代碼來獲取信息,它顯示了一個錯誤..LINQ查詢聯接

var mails = from m in entity.mailboxes 
      join p in entity.ordinary_user_profile_info on m.from_id equals p.user_id 
      select new MailList 
      { 
       mid = m.m_id, 
       mfrom = m.**from_id,** // Error occours here 
       mfomname = p.username, 
       msubject = m.subject 
      }; 

錯誤是: 「詮釋mailbox.from_id」

無法隱式轉換類型'詮釋?到'int'。一個顯式轉換存在(是否缺少強制轉換?)

我宣佈m_idfrom_id在DB以及在郵件列表類int。

+0

**(1)** MailList.mfrom是一個int類型嗎? **(2)**使用工具欄上的「{}」按鈕編輯您的問題並設置您的代碼的格式。 – gideon 2011-01-27 08:08:18

回答

4
var mails = from m in entity.mailboxes 
      join p in entity.ordinary_user_profile_info on m.from_id equals p.user_id 
      select new MailList 
      { 
       mid = m.m_id, 
       mfrom = m.from_id ?? 0, 
       mfomname = p.username, 
       msubject = m.subject 
      }; 
0

試試這個:

​​
5

我猜這應該修復它。

所以詮釋?Nullable type,你需要要麼

(1)定義MailList.mfromint
(2)從int轉換?爲int,像下面

var mails = from m in entity.mailboxes 
      join p in entity.ordinary_user_profile_info on m.from_id equals p.user_id 
      select new MailList 
      { 
       mid = m.m_id, 
       **mfrom = m.from_id.HasValue ? m.from_id.Value : 0** 
       //this is saying is, since the int is nullable, 
       //if it has a value, take it, or return 0 
       mfomname = p.username, 
       msubject = m.subject 
      }; 

更新


一個進一步的研究之後,好像@abatishchev解決方案與null-coalescing operator是要走的正確方式,根據msdn和@Konstantin上的評論提及Nullable.GetValueOrDefault(T)也是比較正確的。

+3

對於這種情況,有Nullable .GetValueOrDefault方法。 – 2011-01-27 08:27:10