前几天遇到一个问题,找了好久才找到解决办法。不过也很开心,终于解决了。
问题:前端当我数据为空的时候不赋值,传到后台也为空的时候(注意:是Null不是""),SqlCommand对传送的参数中如果字段的值是NULL具然不进行更新操作。
插入、更新操作都不进行,现在咱们拿插入为例(更新同理)。
例:
public bool Insert(SysNotify notify)
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@Title", notify.Title),
new SqlParameter("@NotifyType", notify.NotifyType),
new SqlParameter("@NotifyContent", notify.NotifyContent)
}; string sqlStr = @" INSERT INTO SysNotify(Title, NotifyType, NotifyContent)
VALUES(@Title, @NotifyType, @NotifyContent) "; return DbHelper.ExecuteNonQuery(CommandType.Text, sqlStr, parameters);
}
这里就是当notify.Title为Null时,就会报错,所以要对notify.Title这个字段处理一下。
解决办法:
我使用扩展方法封装了一个静态方法:
#region 判断数据为空时,获取其DBNull的值 徐悦 2019年2月23日17:16:35
/// <summary>
/// 判断数据为空时,获取其DBNull的值
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object GetDBNull(this object value)
{
if (value == null)
{
return DBNull.Value;
}
return value;
}
#endregion
然后按照下面这种形式调用就可以处理数据为空时的处理
public bool Insert(SysNotify notify)
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@Title", notify.Title.GetDBNull()),
new SqlParameter("@NotifyType", notify.NotifyType),
new SqlParameter("@NotifyContent", notify.NotifyContent.GetDBNull())
}; string sqlStr = @" INSERT INTO SysNotify(Title, NotifyType, NotifyContent)
VALUES(@Title, @NotifyType, @NotifyContent) "; return DbHelper.ExecuteNonQuery(CommandType.Text, sqlStr, parameters);
}
按照标红处方式使用就可以解决当数据为空时,SqlCommond执行不成功的问题。
bingo(o゜▽゜)o☆[BINGO!]