Dav*_*och 35 .net c# sql-server naming-conventions
我厌倦了编写以下代码:
/* Commenting out irrelevant parts
public string MiddleName;
public void Save(){
SqlCommand = new SqlCommand();
// blah blah...boring INSERT statement with params etc go here. */
if(MiddleName==null){
myCmd.Parameters.Add("@MiddleName", DBNull.Value);
}
else{
myCmd.Parameters.Add("@MiddleName", MiddleName);
}
/*
// more boring code to save to DB.
}*/
Run Code Online (Sandbox Code Playgroud)
所以,我写了这个:
public static object DBNullValueorStringIfNotNull(string value)
{
object o;
if (value == null)
{
o = DBNull.Value;
}
else
{
o = value;
}
return o;
}
// which would be called like:
myCmd.Parameters.Add("@MiddleName", DBNullValueorStringIfNotNull(MiddleName));
Run Code Online (Sandbox Code Playgroud)
如果这是一个很好的方法,那么你会建议什么作为方法名称?DBNullValueorStringIfNotNull有点冗长和令人困惑.
我也愿意完全缓解这个问题.我喜欢这样做:
myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName);
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为"运营商'??' 不能应用于'string和'System.DBNull'"类型的操作数.
如果重要的话,我可以使用C#3.5和SQL Server 2005.
Ada*_*son 56
将您的任何一个值转换为object,然后编译.
myCmd.Parameters.Add("@MiddleName", MiddleName==null ? (object)DBNull.Value : MiddleName);
Run Code Online (Sandbox Code Playgroud)
Ser*_*y K 18
你可以避开显式的object使用SqlString.Null,而不是DBNull.Value:
MiddleName ?? SqlString.Null
Run Code Online (Sandbox Code Playgroud)
int,datetime等有相应的类型.这是一个包含更多示例的代码段:
cmd.Parameters.AddWithValue("@StartDate", StartDate ?? SqlDateTime.Null);
cmd.Parameters.AddWithValue("@EndDate", EndDate ?? SqlDateTime.Null);
cmd.Parameters.AddWithValue("@Month", Month ?? SqlInt16.Null);
cmd.Parameters.AddWithValue("@FormatID", FormatID ?? SqlInt32.Null);
cmd.Parameters.AddWithValue("@Email", Email ?? SqlString.Null);
cmd.Parameters.AddWithValue("@ZIP", ZIP ?? SqlBoolean.Null);
Run Code Online (Sandbox Code Playgroud)
Chr*_*sic 11
就个人而言,这就是我对扩展方法所做的事情(确保它进入静态类)
public static object GetStringOrDBNull(this string obj)
{
return string.IsNullOrEmpty(obj) ? DBNull.Value : (object) obj
}
Run Code Online (Sandbox Code Playgroud)
然后你就拥有了
myCmd.Parameters.Add("@MiddleName", MiddleName.GetStringOrDBNull());
Run Code Online (Sandbox Code Playgroud)
myCmd.Parameters.Add("@MiddleName", MiddleName ?? (object)DBNull.Value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36000 次 |
| 最近记录: |