public virtual TModel Update(TModel instance) { DbCommand cmd = db.GetSqlStringCommand("a");//随便赋一个,因为参数不能为空 string sql = "update " + TableName + " set "; PropertyInfo[] Properties = instance.GetType().GetProperties(); var Fields = DbTableFields; string temp = ""; foreach (var property in Properties) { if (property.Name.ToLower() == PrimaryKeyName.ToLower()) { continue; } foreach (var obj in Fields) { //如果属性没有相应的数据库字段则不处理 if (obj.Key.Equals(property.Name, StringComparison.OrdinalIgnoreCase)) { if (property.CanWrite && property.CanRead) { temp += "," + property.Name + "=@" + property.Name + ""; var pValue = property.GetValue(instance, null);// instance.GetValue(property); if (pValue == null || !pValue.GetType().IsEnum) { db.AddInParameter(cmd, "@" + property.Name, instance.GetPropertyDbType(property), pValue); } else { db.AddInParameter(cmd, "@" + property.Name, DbType.Int32, Convert.ToInt32(pValue)); } } break; } } } if (temp != "") { temp = temp.Substring(1); sql += temp; sql += " where " + PrimaryKeyName + "=@" + PrimaryKeyName + ""; db.AddInParameter(cmd, "@" + PrimaryKeyName, typeof(TKey).ToDbType(), instance.GetValue(PrimaryKeyName) ?? DBNull.Value); cmd.CommandText = sql; db.ExecuteNonQuery(cmd); } //return (TModel)instance; return(instance); }
public virtual List <TModel> Update(List <TModel> instances) { DbCommand cmd = db.GetSqlStringCommand("a");//随便赋一个,因为参数不能为空 var sqlUpdate = string.Empty; for (var i = 0; i < instances.Count(); i++) { var instance = instances.ElementAt(i); string sql = "update " + TableName + " set "; PropertyInfo[] Properties = instance.GetType().GetProperties(); var Fields = DbTableFields; string temp = ""; foreach (var property in Properties) { if (property.Name.ToLower() == PrimaryKeyName.ToLower()) { continue; } foreach (var obj in Fields) { //如果属性没有相应的数据库字段则不处理 if (obj.Key.Equals(property.Name, StringComparison.OrdinalIgnoreCase)) { if (property.CanWrite && property.CanRead) { temp += "," + property.Name + "=@" + property.Name + "" + i + ""; var pValue = property.GetValue(instance, null); //instance.GetValue(property); if (pValue == null || !pValue.GetType().IsEnum) { db.AddInParameter(cmd, "@" + property.Name + i, instance.GetPropertyDbType(property), pValue); } else { db.AddInParameter(cmd, "@" + property.Name + i, DbType.Int32, Convert.ToInt32(pValue)); } } break; } } } if (temp != "") { temp = temp.Substring(1); sql += temp; sql += " where " + PrimaryKeyName + "=@" + PrimaryKeyName + "" + i + ""; db.AddInParameter(cmd, "@" + PrimaryKeyName + i, typeof(TKey).ToDbType(), instance.GetValue(PrimaryKeyName) ?? DBNull.Value); sqlUpdate += ";" + sql; //cmd.CommandText = sql; //db.ExecuteNonQuery(cmd); } } if (!(string.IsNullOrEmpty(sqlUpdate) || string.IsNullOrEmpty(sqlUpdate))) { sqlUpdate = sqlUpdate.Substring(1); cmd.CommandText = sqlUpdate; db.ExecuteNonQuery(cmd); } //return instances.Select(item=>(TModel)item); return(instances); }