泛型——转化实体类的方法

1、DataTable转为实体类List

public static class ConvertHelper where T : new()
{
    /// 
    /// 将DataTable转为实体类List
    /// 
    /// 
    /// 
    public static IList ConvertToModel(DataTable dt)
    {
        //定义集合
        IList ts = new List();
        T t = new T();
        string tempName = "";
        //获取此模型的公共属性
        PropertyInfo[] propertys = t.GetType().GetProperties();
        foreach (DataRow row in dt.Rows)
        {
            t = new T();
            foreach (PropertyInfo pi in propertys)
            {
                tempName = pi.Name;
                //检查DataTable是否包含此列
                if (dt.Columns.Contains(tempName))
                {
                    //判断此属性是否有set
                    if (!pi.CanWrite)
                        continue;
                    object value = row[tempName];
                    if (value != DBNull.Value)
                        pi.SetValue(t, value, null);
                }
            }
            ts.Add(t);
        }
        return ts;
    }
}
public static List ToDataList(this DataTable dt)
{
    var list = new List();
    var plist = new List(typeof(T).GetProperties());
    foreach (DataRow item in dt.Rows)
    {
        T s = Activator.CreateInstance();
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
            if (info != null)
            {
                try
                {
                    if (!Convert.IsDBNull(item[i]))
                    {
                        object v = null;
                        if (info.PropertyType.ToString().Contains("System.Nullable"))
                        {
                            v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                        }
                        else
                        {
                            v = Convert.ChangeType(item[i], info.PropertyType);
                        }
                        info.SetValue(s, v, null);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                }
            }
        }
        list.Add(s);
    }
    return list;
}

2、DataTable转实体类

public static T ToDataDto(this DataTable dt)
{
    T s = Activator.CreateInstance();
    if (dt == null || dt.Rows.Count == 0)
    {
        return s;
    }
    var plist = new List(typeof(T).GetProperties());
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
        if (info != null)
        {
            try
            {
                if (!Convert.IsDBNull(dt.Rows[0][i]))
                {
                    object v = null;
                    if (info.PropertyType.ToString().Contains("System.Nullable"))
                    {
                        v = Convert.ChangeType(dt.Rows[0][i], Nullable.GetUnderlyingType(info.PropertyType));
                    }
                    else
                    {
                        v = Convert.ChangeType(dt.Rows[0][i], info.PropertyType);
                    }
                    info.SetValue(s, v, null);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
            }
        }
    }
    return s;
}

3、实体集合转换为DataTable

/// 
/// 将实体集合转换为DataTable
/// 
/// 实体类型
/// 实体集合
public static DataTable ToDataTable(List entities)
{
    var result = CreateTable();
    FillData(result, entities);
    return result;
}

/// 
/// 创建表
/// 
private static DataTable CreateTable()
{
    var result = new DataTable();
    var type = typeof(T);
    foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
    {
        var propertyType = property.PropertyType;
        if ((propertyType.IsGenericType) && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
            propertyType = propertyType.GetGenericArguments()[0];
        result.Columns.Add(property.Name, propertyType);
    }
    return result;
}

/// 
/// 填充数据
/// 
private static void FillData(DataTable dt, IEnumerable entities)
{
    foreach (var entity in entities)
    {
        dt.Rows.Add(CreateRow(dt, entity));
    }
}

/// 
/// 创建行
/// 
private static DataRow CreateRow(DataTable dt, T entity)
{
    DataRow row = dt.NewRow();
    var type = typeof(T);
    foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
    {
        row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
    }
    return row;
}

你可能感兴趣的:(c#,开发语言)