【问题标题】:LINQ query JoinsLINQ 查询联接
【发布时间】:2011-01-27 08:02:35
【问题描述】:

当我使用下面的代码检索信息时,它显示一个错误..

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'。存在显式转换(您是否缺少演员表?)

我已在 DB 和 MailList 类中将 m_idfrom_id 声明为 int。

【问题讨论】:

  • (1) MailList.mfromint?? (2) 使用工具栏上的“{}”按钮编辑您的问题并格式化您的代码。

标签: c# .net linq group-by


【解决方案1】:

我猜这应该可以解决它。

所以 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 的说法,似乎带有 null-coalescing operator@abatishchev 解决方案是正确的方法,就像 @Konstantin 上的cmets提到Nullable.GetValueOrDefault(T)也比较正确。

【讨论】:

  • 对于这种情况有 Nullable.GetValueOrDefault 方法。
  • 感谢@Konstantin 不知道这种方法! =)
【解决方案2】:
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
            };

【讨论】:

    【解决方案3】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多