【问题标题】:Left outer join in LINQ is showing exceptionLINQ 中的左外连接显示异常
【发布时间】:2010-04-27 06:01:04
【问题描述】:

我收到以下异常:

null 值不能分配给 System.Int32 类型的成员,该成员是非 可空值类型。

下面是我的 LINQ 语句,其中 QuestionId 是我表中的主键:

var questionViewsData =
      from questionViews in objDc.SC_QuestionsViews
      join questions in objDc.SC_Questions
      on questionViews.QuestionId equals questions.QuestionId into qs
      from questions in qs.DefaultIfEmpty()
      where questionViews.CreatedDate.Date == new DateTime(2010, 4,27)
      select new 
      {
          Selected =(questions == null ?-1:questions.QuestionId),
          QuestioinTitle = questions.Title,
          VotesCount = questions.VotesCount 
      };

【问题讨论】:

  • 请使用适当的日志记录来找出正在生成的 SQL,并用它来编辑问题 - 这样会更容易诊断。

标签: c# linq


【解决方案1】:

换行

where questionViews.CreatedDate.Date == new DateTime(2010, 4,27)

where questionViews.CreatedDate == new DateTime(2010, 4, 27)

作为你可以运行的测试

where questionViews.CreatedDate > new DateTime(2010, 4, 26)

注意如果我在 LinqPad c# 语句中包含 .Date,我会收到以下错误消息,并且删除 .Date 允许语句运行。

System.Nullable<System.DateTime>' does not contain a definition for 'Date' and no
extension method 'Date' accepting a first argument of type
'System.Nullable<System.DateTime>' could be found

【讨论】:

    【解决方案2】:

    对于初学者,请尝试使用以下命令运行它:

    select new 
          {
              Selected = questions.QuestionId,
              QuestioinTitle = questions.Title,
              VotesCount = questions.VotesCount 
          };
    

    你得到了什么?

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 2011-08-04
      • 2011-03-25
      • 2011-08-10
      相关资源
      最近更新 更多