Passing DBNull.Value and Empty textbox value to database(将 DBNull.Value 和 Empty 文本框值传递给数据库)
问题描述
I have some textboxes on my page which can be empty because they are optional and I have this DAL code
parameters.Add(new SqlParameter("@FirstName", FirstName));
parameters.Add(new SqlParameter("@LastName", LastName));
parameters.Add(new SqlParameter("@DisplayName", DisplayName));
parameters.Add(new SqlParameter("@BirthDate", BirthDate));
parameters.Add(new SqlParameter("@Gender", Gender));
Any of those fields can be empty. The problem is when they are empty I receive Procedure XXX requires @FirstName which was not supplied
Then I changed my code to
parameters.Add(new SqlParameter("@FirstName", String.IsNullOrEmpty(FirstName) ? DBNull.Value : (object)FirstName));
parameters.Add(new SqlParameter("@LastName", String.IsNullOrEmpty(LastName) ? DBNull.Value : (object) LastName));
parameters.Add(new SqlParameter("@DisplayName", String.IsNullOrEmpty(DisplayName) ? DBNull.Value : (object) DisplayName));
parameters.Add(new SqlParameter("@BirthDate", BirthDate.HasValue ? (object)BirthDate.Value : DBNull.Value));
parameters.Add(new SqlParameter("@Gender", String.IsNullOrEmpty(Gender) ? DBNull.Value : (object) Gender));
But this looks messy to me especially the casting to object
because ternary statement requires both value to be the same type.
Why is empty string or null string not treated NULL
in the database? If I have to convert this to DBNull.Value
is there a cleaner way? Saving the value as empty string in the database could have helped but query for NULL
in the database will get messy too
Please give your advice on common practices or something close to that.
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;
}
这篇关于将 DBNull.Value 和 Empty 文本框值传递给数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 DBNull.Value 和 Empty 文本框值传递给数据库


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01