DataTable与实体对象互转

/// 
/// 将DataTable转为实体对象
/// 
/// 
/// 
/// 
public static List GetEntityFromDataTable(DataTable sourceDT) where T : class
{
    List list = new List();
    // 获取需要转换的目标类型
    Type type = typeof(T);
    foreach (DataRow dRow in sourceDT.Rows)
    {
        // 实体化目标类型对象
        object obj = System.Activator.CreateInstance(type);
        foreach (var prop in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
        {
            if (prop.GetSetMethod() != null)// 有些属性没有setter
            {
                // 给目标类型对象的各个属性值赋值
                prop.SetValue(obj, dRow[prop.Name], null);
            }
        }

        list.Add(obj as T);
    }
    return list;
}


/// 
/// 将实体列表转为DataTable
/// 
/// 
/// 
/// 
private DataTable GetDataTableFromEntity(List list)
{
    DataTable dt = new DataTable();
    System.Reflection.PropertyInfo[] properties = typeof(ReturnMessages).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
    foreach (System.Reflection.PropertyInfo pro in properties)
    {
        // 添加列
        dt.Columns.Add(pro.Name, pro.PropertyType);
    }

    foreach (T item in list)
    {
        DataRow dr = dt.NewRow();
        foreach (System.Reflection.PropertyInfo pro in properties)
        {
            dr[pro.Name] = item.GetType().GetProperty(pro.Name).GetValue(item, null);
        }

        dt.Rows.Add(dr);
    }
    dt.AcceptChanges();
    return dt;
}

 

你可能感兴趣的:(C#)