1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public bool Insert(T t) where T : BaseModel { //插入实体时要判断一下时间的插入.还可以通过特性来判断一下数据的长度 //约定的id为自增长. var type = typeof(T); var keys = new List(); var values = new List(); var par = new List(); foreach (var item in type.GetProperties()) { var value = item.GetValue(t); if (item.Name.ToLower() == "id") continue; keys.Add(item.Name); values.Add("@" + item.Name); par.Add(new SqlParameter("@" + item.Name, value)); } var c = string.Join(",", keys.ToArray()); var v = string.Join(",", values.ToArray()); var sql = string.Format($"INSERT INTO [{type.Name}] ({c}) " + $"VALUES({v})");
return ExcuteSql(sql, cmd => { foreach (var parameter in par) cmd.Parameters.Add(parameter);
var result = cmd.ExecuteNonQuery(); return result > 0; });
// return RunCmd(sql, par.ToArray()); }
|