#region //执行对单个Entity的更新(这个可以添加额外的约束条件)
/// <summary>
/// 执行对单个Entity的更新
/// </summary>
/// <param name="baseEntity">由控制器组装而来的实体</param>
/// <param name="otherConditions">其他约束条件用(and开头,例如:"and name='王斐'"</param>
public void ExecuteObjectUpdate(BaseEntity baseEntity, string otherConditions)
{
string sql_ = "";//values 之前
try
{
Type type = baseEntity.GetType();
IList<CustomAttributeData> tableAttribute = type.GetCustomAttributesData();//该方法是根据Type属性找到的
string tableName = "";//表名
tableName = (String)tableAttribute[0].ConstructorArguments[0].Value;//解刨Type属性中偶然发现
string operation = "update";//执行操作方法,此处可以考虑将操作类型operation由调用者确定
PropertyInfo[] propertyList = type.GetProperties();//返回PropertyInfo类型,用于取得该类的属性的信息
//生成SQL语句
string propertyName = "";//属性名
string propertyValue = "";//属性值
sql_ = operation + " " + tableName + " set ";
int updateCount = 0;//用于计数更新
for (int i = 1; i < propertyList.Length; i++)
//这里考虑并没有写死跟添加一样,也从0开始,有一段时间考虑想从i=1开始,
//但是存在部分情况主键可以改变的情况,因此,这里会默认的将首字段进行拼接,
//会出现update tableName set PKName=value.... where PKName=value;的情况
//个人认为这并不影响
//2015年5月28日02:14:26
//由于部分主键是自增的,如果默认主键参与跟新,则会因为自增字段不能update而报错
//但是没有找到合适方法
//这里还是从第2个开始判断
{
//propertyList.Add("");
propertyName = propertyList[i].Name;
propertyValue = GetObjectPropertyValue(type, baseEntity, propertyName);//获取属性值
if (propertyValue != null)
{
if (updateCount != 0)//判断是否是第一个更新的字段如果是则不添加逗号
{
sql_ += " , ";
}
sql_ += "[" + propertyName + "]"+"= N'{0}'";
sql_ = string.Format(sql_, propertyValue);
updateCount++;
}
}
string PKPropertyName = propertyList[0].Name;//此处还在考虑 是否需要解析一下 ,可以改为支持两个主键或者以上
string PKPropertyValue = GetObjectPropertyValue(type, baseEntity, PKPropertyName);
sql_ = sql_ + " where " + PKPropertyName + "=N'{0}'" + " " + otherConditions;//此处添加而外约束条件跟主键
sql_ = String.Format(sql_, PKPropertyValue);
OpenDb();
SqlCommand cm = new SqlCommand(sql_, conn);
cm.ExecuteNonQuery();
cm.Dispose();
cm = null;
CloseDb();
}
catch (Exception e)
{
throw new Exception(e.ToString() + " " + sql_);
}
}
#endregion