Is there a more elegant form for assigning NULL to InsertCommand's NVarChar?

纵饮孤独 提交于 2019-12-07 15:55:15

问题


This code works for me very well:

if (someStr == null)
  da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = DBNull.Value;
else
  da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = someStr;

But my intuition tells me that there may be a one-liner version of it. Something like:

  da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = someStr==null ? DBNull.Value : someStr ;

But the one-liner I just posted above fails of course because DBNull.Value doesn't cast to String.

Is there a way to accomplish the one liner I so desire?


回答1:


You could cast someStr to an object

For example:

da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = someStr==null ? DBNull.Value : (object)someStr;

Or you could do as Oded and Servy suggested and use an extension method. While it may add a few lines of code it will save you from duplicate code.

As Servy pointed out, putting it on object could lead to clutter. For this reason I would put it on SqlParameter

public static void SetValue(this SqlParameter parameter, object value)
{
    parameter.Value = value == null ? DBNull.Value : value;
}

Then use it like so

da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).SetValue(someStr);



回答2:


Create a function or extension method that will do the test and make the assignments as needed. Pass in someStr and the parameter name.

You will then be able to set the parameter in one line.




回答3:


You can use the following extension method (or make it a non-extension method if you prefer)

public static object ConvertNull(this object obj)
{
    return obj ?? DBNull.Value;
}

You can then do:

da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = someStr.ConvertNull()



回答4:


da.InsertCommand.Parameters.Add("@SOMESTR", SqlDbType.NVarChar).Value = ((object)someStr) ?? DBNull.Value; 



回答5:


Write a stored procedure for inserting, set default value for your argument as null, Use that stored procedure for your insert command, then don't just pass that argument to that sproc..



来源:https://stackoverflow.com/questions/12981012/is-there-a-more-elegant-form-for-assigning-null-to-insertcommands-nvarchar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!