本文介绍了是否有一个更优雅的形式来的InsertCommand的分配的NVarChar NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码工作对我来说非常好:

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 ;



不过,当然,因为的DBNull的单行我刚刚张贴以上失败。值不强制转换为字符串。

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?

推荐答案

您可以施放someStr的一个对象。

You could cast someStr to an object

例如:

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

或者你可以做的俄德和Servy建议和使用的扩展方法。虽然它可能添加几行代码就可以使你免于重复的代码。

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.

由于Servy指出的那样,把它放在对象可能会导致混乱。为此,我会把它放在的SqlParameter

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);

这篇关于是否有一个更优雅的形式来的InsertCommand的分配的NVarChar NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-20 22:20