今天用LINQ的update出现问题了,LINQ的BUG不少,呵呵,所以自己把TSQL拿出来,做了一个封装,适用的所有表,更新有两种,普通更新和记数更新
看代码:这两个方法是写在DAL里的数据操作基类里的,只有它的子类可以用它,所以用protected做为限制
/// <summary>
/// 通用更新方法
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="param">参数列表,奇数为字段,偶数为他前一奇数对应的值,索引0为要更新的主键,1为主键值</param>
protected virtual void Update(string tableName, params object[] param)
{
StringBuilder sbSql = new StringBuilder();
List<object> listParasm = new List<object>();
listParasm.Add(param[0]);
listParasm.Add(param[1]);
int index = listParasm.Count;
sbSql.AppendFormat("UPDATE [{0}] SET ", tableName);
if (index == 0)
{
return;
}
else
{
for (int i = 2; i < param.Count(); i += 2)
{
if (param[index + 1].GetType() == typeof(string))
sbSql.AppendFormat("{{{0}}} = '{{{1}}}',", index, index + 1);
else
sbSql.AppendFormat("{{{0}}} = {{{1}}},", index, index + 1);
listParasm.Add(param[index]);
listParasm.Add(param[index + 1]);
index++;
index++;
}
sbSql.Remove(sbSql.Length - 1, 1);//移除最后一个逗号
}
sbSql.Append(" WHERE [{0}] = {1}");
db.ExecuteCommand(sbSql.ToString(), listParasm.ToArray());
}
/// <summary>
/// 计数更新
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="param">参数列表,索引0为主键名,1表主键值,2为要计数的字段,3为增量</param>
protected virtual void UpdateForCount(string tableName, params object[] param)
{
string sql = "update [{0}] set [{3}]=[{3}]+{4} where [{1}]={2}";
List<object> listParasm = new List<object>
{
tableName,
param[0],
param[1],
param[2],
param[3],
};
db.ExecuteCommand(string.Format(sql, listParasm.ToArray()));
}
本文转自博客园张占岭(仓储大叔)的博客,原文链接:MVC LINQ中用封装的TSQL通用更新方法,如需转载请自行联系原博主。