码迷,mamicode.com
首页 > 数据库 > 详细

将实体类、匿名对象转换为SqlParameter列表

时间:2017-12-11 11:26:30      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:body   property   rar   实体   数组   into   pre   insert   实体类   

/// <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();

  

将实体类、匿名对象转换为SqlParameter列表

标签:body   property   rar   实体   数组   into   pre   insert   实体类   

原文地址:http://www.cnblogs.com/XuPengLB/p/8021695.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!