/// <summary> /// <remarks> /// <para>将实体类/匿名对象转换为SqlParameter列表</para> /// <para>示例1: 实体类</para> /// <para>EntityClass entityClass = new EntityClass(){ Id = 1 , Name="名称"}; SqlParameter[] parms = entityClass.ToSqlParameterArray()</para> /// <para>示例2: 匿名对象</para> /// <para>var anonymousObject = new { Id = 1 , Name="名称"}; SqlParameter[] parms = anonymousObject.ToSqlParameterArray()</para> /// <para>注意:SqlParameter(string parameterName, object value)的参数parameterName均为实体类/匿名对象属性的小写形式的副本。</para> /// <para>因此,对应sql参数应为小写形式,例如:insert into tbname(name) values(@name)</para> /// </remarks> /// </summary> /// <param name="obj">实体类/匿名对象</param> /// <returns>SqlParameter参数数组</returns> public static SqlParameter[] ToSqlParameterArray<T>(this T entityClass) where T : class { List<SqlParameter> parms = new List<SqlParameter>(); 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();