1. 程式人生 > >將實體類、匿名對象轉換為SqlParameter列表

將實體類、匿名對象轉換為SqlParameter列表

ins 名稱 rem return parameter 實體 mark continue rar

/// <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列表