将Null值插入整数列

7

我希望通过前端将空值插入到数据类型为Int的列中。

我使用了以下代码:

POP.JobOrderID = Convert.ToInt32(DBNull.Value);

但是我不能插入空值,会抛出错误,例如“无法从DBNull转换为其他类型的对象”:
如何插入NULL值?
5个回答

8
如果您想这样做,POP.JobOrderID 应该是 int? 类型(可空的 nullable int),而不是 int。

POP是一个对象,JobOrderID是整数。如何像这样分配? - thevan
我正在使用三层架构。我会像问题中所提供的那样传递参数。如何在此应用int?(可空) - thevan

5

kleinohad是正确的。此外,你应该分配null而不是DBNull.Value


我正在使用三层架构。我将像问题中提供的那样传递参数。如何在其中应用int?(可为空) - thevan

4

使用Nullable<Int32>或者别名:int?

POP.JobOrderID = 5;
// or
POP.JobOrderID = null;

在ADO.NET中的使用:

command.Parameters.AddWithValue("@JobOrderId", POP.JobOrderID ?? DBNull.Value);

这相当于:

POP.JobOrderID.HasValue ? POP.JobOrderID.Value : DBNull.Value;

2

This

   POP.JobOrderID = new Nullable<Int32>();

如果JobOrderID是可空类型(int?),那么这也应该可以工作。
祝好。

0

像这样:

 POP.JobOrderID = null;    // JobOrderID should be of type int? which is a nullable-int

希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接