通用的通过模型插入或更新数据库

时间:2022-05-20 13:52:23
public class DALInsertUpdate<T> where T : new()
{
/// <summary>
/// 通过模型把非(KeyAttribute)属性插入到指定表
/// </summary>
/// <param name="TableName">要插入到的表名</param>
/// <param name="Model">要插入的模型</param>
/// <returns></returns>
public int Insert(string TableName, T Model)
{
var Name = new StringBuilder();
var Value = new StringBuilder();
var Parame = new List<SqlParameter>();
PropertyInfo[] propertys
= Model.GetType().GetProperties();
foreach (var item in propertys)
{
if (null==item.GetCustomAttribute(typeof(KeyAttribute)))
{
Name.Append(item.Name).Append(
",");
Value.Append(
"@").Append(item.Name).Append(",");
Parame.Add(
new SqlParameter("@"+item.Name,item.GetValue(Model, null)));
}
}
Name.Remove(Name.Length
- 1, 1);
Value.Remove(Value.Length
- 1, 1);
string Sql = string.Format("INSERT INTO {0} ({1})VALUES({2})", TableName, Name.ToString(), Value.ToString());
return SqlHelper.ExecuteNonQuery(SqlHelper.GetConnSting(), CommandType.Text, Sql.ToString(), Parame.ToArray());

}
/// <summary>
/// 通过模型更新指定(KeyAttribute)属性所指向的记录
/// </summary>
/// <param name="TableName">要更新的表名</param>
/// <param name="Model">要更新的模型</param>
/// <returns></returns>
public int Update(string TableName, T Model)
{
PropertyInfo[] propertys
= Model.GetType().GetProperties();
var str = new StringBuilder();
var where =new StringBuilder("");
var Parame = new List<SqlParameter>();
foreach (var item in propertys)
{
if (null!=item.GetCustomAttribute(typeof(KeyAttribute)))
{
where.Append(item.Name).Append("=").Append("@").Append(item.Name);
Parame.Add(
new SqlParameter("@" + item.Name, item.GetValue(Model, null)));

}
else
{
str.Append(item.Name).Append(
"=@").Append(item.Name).Append(",");
Parame.Add(
new SqlParameter("@" + item.Name, item.GetValue(Model, null)));
}
}
str.Remove(str.Length
- 1, 1);
if (string.IsNullOrEmpty(where.ToString())) throw new Exception("没有找到PrimaryKey,无法更新数据库!");
string sql = string.Format("UPDATE {0} SET {1} WHERE {2} ", TableName, str.ToString(), where.ToString());
return SqlHelper.ExecuteNonQuery(SqlHelper.GetConnSting(), CommandType.Text, sql.ToString(), Parame.ToArray());
}
}