Passing DBNull.Value and Empty textbox value to database [duplicate]

☆樱花仙子☆ 提交于 2019-12-01 03:29:53

First, there are 2 more handy overloads:

command.Parameters.Add("@name").Value = value;

or

command.Parameters.AddWithValue("@name", value);

Personally I use the following extension method:

public static object DbNullIfNull(this object obj)
{
    return obj != null ? obj : DBNull.Value;
}

command.Parameters.AddWithValue("@name", value.DbNullIfNull());

or

public static object DbNullIfNullOrEmpty(this string str)
{
    return !String.IsNullOrEmpty(str) ? str : (object)DBNull.Value;
}

A little re-factoring might make code less messy. Try this

dbParams.Add(SetDBNullIfEmpty("@FirstName", FirstName));
dbParams.Add(SetDBNullIfEmpty("@LastName", LastName));
dbParams.Add(SetDBNullIfEmpty("@DisplayName", DisplayName));
dbParams.Add(SetDBNullIfEmpty("@BirthDate", BirthDate));
dbParams.Add(SetDBNullIfEmpty("@Gender", Gender));

private SqlParameter SetDBNullIfEmpty(string parmName, string parmValue)
{
    return new SqlParameter(parmName, String.IsNullOrEmpty(parmValue) ? DBNull.Value : (object)parmValue));
}

You can default the parameters in the stored procedure, making them optional.

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