【问题标题】:The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type不能将 null 值分配给 System.Int32 类型的成员,该类型是不可为 null 的值类型
【发布时间】:2013-04-15 10:15:16
【问题描述】:

运行此代码。在本地开发服务器上运行良好,但在实时服务器上运行良好。

try
{
    var qq =
    db.tblConstructReleaseDownloads
    .Where(c => c.UserID.HasValue && c.UserID.Value == userID)
    .OrderBy(c => c.DateStarted)
    .ThenBy(c => c.ReleaseID);

    var query = db.GetCommand(qq).CommandText;
    HttpContext.Current.Response.Write(query + "<br><br>");

    foreach (var d in qq)
    {
        HttpContext.Current.Response.Write("ID:" + d.ID + "<br>");
    }

这会引发错误:

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

它打印出来的命令文本是:

SELECT     ID, ReleaseID, IP, DateCompleted, BytesServed, UserID, DateStarted, BytesPerSecond, TrackerVisitID
FROM         tblConstructReleaseDownloads AS t0
WHERE     (UserID IS NOT NULL) AND (UserID = @p0)
ORDER BY DateStarted, ReleaseID

我在实时数据库上运行此查询,它工作正常,没有错误。

有人知道是什么原因造成的吗?

【问题讨论】:

    标签: c# asp.net sql linq sql-server-2008


    【解决方案1】:

    查询返回的其中一列在实时服务器上的数据库中包含 NULL 值,但在开发服务器上不包含。
    因为域模型中的相应属性定义为int 而不是int?,所以您应该将该列标记为不可为空

    【讨论】:

    • 我正在查看查询返回的结果,所有相关列都不包含空值。 UserID、dateStarted 和 releaseID 都有非空值。
    • @TomGullen:该查询中有更多列。每个都将被分配给您的域模型中的一个属性,并可能导致该错误。您还需要查看BytesServedBytesPerSecondTrackerVisitID。我怀疑最后一个是问题所在。
    • 谢谢,这成功了!我更改了查询以仅选择我需要的行。将确保我的域模型也与数据库匹配。
    【解决方案2】:

    如果您使用的是 MVC,请检查您的模型。在我检查模型并将 int 值更改为 Nullable int 之前,我为此挣扎了大约 3 个小时。现在就像一个魅力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      相关资源
      最近更新 更多