#region //执行对单个Entity的插入
///
/// 执行对单个Entity的插入(多表操作,表中含有自增字段慎用) 返回值是Entity的第一个属性
///
///
public string ExecuteObjectInput(BaseEntity baseEntity, string tableName)
{
string sql_ = "";//values 之前
try
{
Type type = baseEntity.GetType();//得到对象类型
IList
//string tableName = "";//表名
//tableName = (String)tableAttribute[0].ConstructorArguments[0].Value;//解刨Type属性中偶然发现
string operation = "insert into ";//执行操作方法
PropertyInfo[] propertyList = type.GetProperties();//返回PropertyInfo类型,用于取得该类的属性的信息
//生成SQL语句
string values = "";//values( 之后 最后一起拼装起来
string propertyName = "";//属性名
string propertyValue = "";//属性值
sql_ = operation + " " + tableName + " ( ";
int inputCount = 0;//用于计数新增
for (int i = 0; i < propertyList.Length; i++)//这个从Entity第一个属性开始就解析,主要因为添加时候只要主属性不是自增的就需要填写
{
//propertyList.Add("");
propertyName = propertyList[i].Name;
propertyValue = GetObjectPropertyValue(type, baseEntity, propertyName);//获取属性值
if (propertyValue != null)
{
if (inputCount != 0)
{
sql_ += " , ";
values += " , ";
}
sql_ += "["+propertyName+"]";
values += " N'{0}' ";
values = string.Format(values, propertyValue);
inputCount++;
}
}
sql_ = sql_ + ") output inserted.{0} values(" + values + ")";
sql_ = string.Format(sql_, propertyList[0].Name);
OpenDb();
SqlCommand cm = new SqlCommand(sql_, conn);
//ulong returnId = cm.ExecuteNonQuery();
string returnId =cm.ExecuteScalar().ToString();
cm.Dispose();
cm = null;
CloseDb();
return returnId;
}
catch (Exception e)
{
throw new Exception(e.ToString() + " " + sql_);
}
}
#endregion