无法将null值分配给类型为System.Int32的成员,该类型是非可空值类型

Tom*_*len 2 c# sql linq asp.net sql-server-2008

运行此代码.在本地开发服务器上正常工作,但在实时服务器上不能.

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

这会引发错误:

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
Run Code Online (Sandbox Code Playgroud)

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

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

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

有人有任何想法是什么导致这个?

Dan*_*rth 7

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

  • @TomGullen:该查询中有更多列.每个都将分配给您的域模型中的属性,并可能导致该错误.您还需要查看`BytesServed`,`BytesPerSecond`和`TrackerVisitID`.我怀疑最后一个是问题所在. (2认同)