////// /// 实体类/匿名对象////// ///将实体类/匿名对象转换为SqlParameter列表 ///示例1: 实体类 ///EntityClass entityClass = new EntityClass(){ Id = 1 , Name="名称"}; SqlParameter[] parms = entityClass.ToSqlParameterArray() ///示例2: 匿名对象 ///var anonymousObject = new { Id = 1 , Name="名称"}; SqlParameter[] parms = anonymousObject.ToSqlParameterArray() ///注意:SqlParameter(string parameterName, object value)的参数parameterName均为实体类/匿名对象属性的小写形式的副本。 ///因此,对应sql参数应为小写形式,例如:insert into tbname(name) values(@name) ///SqlParameter参数数组 public static SqlParameter[] ToSqlParameterArray(this T entityClass) where T : class{ List parms = new List (); PropertyInfo[] propertys = entityClass.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { // 判断此属性是否有Getter if (!pi.CanRead) { continue; } object value = pi.GetValue(entityClass); parms.Add(new SqlParameter("@" + pi.Name.ToLower(), value)); } return parms.ToArray();}/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/public class EntityClass{ public int Id { get; set; } public string Name { get; set; } public int Age { get; set; }}//使用示例://1.实体类EntityClass ec = new EntityClass(){ Name= "长毛象", Age = 2};//SqlParameter[] parms = ec.ToSqlParameterArray();var parms = ec.ToSqlParameterArray();//2.匿名类var ec = new{ Name = "长毛象", Age = "2"};//SqlParameter[] parms = ec.ToSqlParameterArray();var parms = ec.ToSqlParameterArray();