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

时间:2013-04-22 13:27:40

标签: c# asp.net sql linq 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>");
    }

这会引发错误:

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

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

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

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

If you are using MVC check your model. I wrestled with this for about 3 hours before I checked the model and changed the int value to Nullable int. Works like a charm now.