LINQ查询加入

Mut*_*thu 0 .net c# 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
            };
Run Code Online (Sandbox Code Playgroud)

错误是:

"int?mailbox.from_id"

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

我在DB和MailList类中声明了m_idfrom_idint.

gid*_*eon 5

我猜这应该解决它.

那么int?是一个空类型,你需要要么

(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
            };
Run Code Online (Sandbox Code Playgroud)

更新


经过多一点研究后,似乎@abatishchev解决方案与null-coalescing运算符是正确的方法,根据msdn,和@Konstantin一样,提到的注释Nullable.GetValueOrDefault(T)也更正确.

  • 对于这种情况,存在Nullable <T> .GetValueOrDefault方法. (3认同)