从 C# DbCommand 向 SQL DB 插入 NULL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9801649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting NULL to SQL DB from C# DbCommand
提问by SkonJeet
DbParameter param = comm.CreateParameter();
param = comm.CreateParameter();
param.ParameterName = "@StaffId";
if (!string.IsNullOrEmpty(activity.StaffId))
param.Value = activity.StaffId;
param.DbType = DbType.String;
comm.Parameters.Add(param);
The above does not work (obviously), object not instantiated. I am attempting to insert a NULL into the database when StaffId is NOT populated. How can I achieve this?
以上不起作用(显然),对象未实例化。当没有填充 StaffId 时,我试图在数据库中插入一个 NULL。我怎样才能做到这一点?
采纳答案by Andrey Gurinov
You can use DBNull.Value when you need to pass NULL as a parameter to the stored procedure.
当您需要将 NULL 作为参数传递给存储过程时,您可以使用 DBNull.Value。
param.Value = DBNull.Value;
Or you can use that instead of your ifoperator:
或者您可以使用它代替您的if运营商:
param.Value = !string.IsNullOrEmpty(activity.StaffId) ? activity.StaffId : (object)DBNull.Value;
回答by adatapost
Try DBNull.Value
尝试 DBNull.Value
if (!string.IsNullOrEmpty(activity.StaffId))
param.Value = activity.StaffId;
else
param.Value=DBNull.Value;
回答by Andomar
You could use DBNull.Value:
你可以使用DBNull.Value:
param.Value = DBNull.Value;
回答by Niko Yakimov
You can always use the null-coalescing operator (??)
您始终可以使用空合并运算符 (??)
param.Value = activity.StaffId ?? (object)DBNull.Value;

