LINQ查询加入

时间:2011-01-27 08:02:36

标签: c# .net linq group-by

当我使用以下代码检索信息时,它会显示错误..

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
            };

错误是:

  

“int?mailbox.from_id”

     

无法隐式转换类型'int?' 'int'。存在显式转换(您是否错过了演员?)

我已在数据库和MailList类中将m_idfrom_id声明为int。

3 个答案:

答案 0 :(得分:5)

我猜这应该解决它。

所以 int?Nullable type,你需要

(1)将MailList.mfrom定义为int
(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
            };

更新


根据msdn的说法,经过一番研究,似乎 @abatishchev 解决方案与null-coalescing operator是正确的方法,并且喜欢 @Konstantin 关于提到的评论Nullable.GetValueOrDefault(T)也更正确。

答案 1 :(得分: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
            };

答案 2 :(得分:0)

试试这个:

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 = (int)m.from_id,  // Error occours here
                mfomname = p.username,
                msubject = m.subject
            };