前幾天遇到一個問題,找了好久才找到解決辦法。不過也很開心,終於解決了。
問題:前端當我數據為空的時候不賦值,傳到后台也為空的時候(注意:是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!]
