I need to use Convert.DBNull for every single null value while adding parameters of sqlCommands. It's tedious because I have a lot of sql commands. So it would be lot easier if there is any way like setting this Object(Convert.DBNull)as parameter whenever it gets a null value as parameter.
Example: I have a code like this:
cmd.Parameters.AddWithValue("@MasterLastModifiedBy", Master.LastModifiedBy);
As variables like Master.LastModifiedBy might be null sometimes, therefore I have to reformat that into this:
cmd.Parameters.AddWithValue("@MasterLastModifiedBy", Master.LastModifiedBy?? Convert.DBNull);
I don't want to do this reformatting in all parameters. So, what else can I do to resolve this problem?
I would suggest using an ORM Library of some sort. Dapper or Entity Framework would be good places to start.
Or you can write your own method to add a null check to each parameter.
Finally (specifically) thinking about last modified date, you could always set it, which would probably simplify a bunch of queries
EDIT:
Your extension method could look like this:
public static class SqlExtensions // needs to be in a static class
{
public static void AddWithValueAndNullCheck(this SqlParameterCollection collection, string parameterName, object value)
{
if (object == null)
{
collection.AddWithValue(parameterName, DBNull.Value);
}
else
{
collection.AddWithValue(parameterName, value);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.