DataTable转换成List<Model> 关键代码

有时候,我们在开发中,需要将DataTable转化为实体,这样的话可以通过属性直接点出来名称,更方便,快捷。

///
/// DataTable转成实体
///
public static class Table2Model
{
#region 公共方法(扩展DataTable)

/// <summary>
///  DataTable转换成T
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="table">需转换的数据table</param>
/// <returns></returns>
public static T ToModel<T>(this DataTable table) where T : new()
{
    T entity = new T();

    foreach (DataRow row in table.Rows)
    {
        foreach (var item in entity.GetType().GetProperties())
        {
            if (row.Table.Columns.Contains(item.Name))
            {
                if (DBNull.Value != row[item.Name])
                {
                    item.SetValue(entity, ChangeType(row[item.Name], item.PropertyType), null);
                }
            }
        }
    }

    return entity;
}

/// <summary>
///  DataTable转换成T
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="table">需转换的数据table</param>
/// <param name="ext">外延表重名需加的前缀</param>
/// <returns></returns>
public static T ToModel<T>(this DataTable table, string ext) where T : new()
{
    T entity = new T();

    foreach (DataRow row in table.Rows)
    {
        foreach (var item in entity.GetType().GetProperties())
        {
            if (row.Table.Columns.Contains(ext + item.Name))
            {
                if (DBNull.Value != row[ext + item.Name])
                {
                    item.SetValue(entity, ChangeType(row[ext + item.Name], item.PropertyType), null);
                }
            }
        }
    }

    return entity;
}

/// <summary>
///  DataTable转换成List<T>
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="table">需转换的数据table</param>
/// <returns></returns>
public static List<T> ToModelList<T>(this DataTable table) where T : new()
{
    List<T> entities = new List<T>();

    foreach (DataRow row in table.Rows)
    {
        T entity = new T();
        foreach (var item in entity.GetType().GetProperties())
        {
            if (row.Table.Columns.Contains(item.Name))
            {
                if (DBNull.Value != row[item.Name])
                {
                    item.SetValue(entity, ChangeType(row[item.Name], item.PropertyType), null);
                }
            }
        }
        entities.Add(entity);
    }

    return entities;
}

#endregion 公共方法(扩展DataTable)

#region 私有方法(Convert.ChangeType处理Nullable<>和非Nullable<>)

/// <summary>
/// 类型转换(包含Nullable<>和非Nullable<>转换)
/// </summary>
/// <param name="value"></param>
/// <param name="conversionType"></param>
/// <returns></returns>
private static object ChangeType(object value, Type conversionType)
{
    // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
    // checking properties on conversionType below.
    if (conversionType == null)
    {
        throw new ArgumentNullException("conversionType");
    } // end if

    // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

    if (conversionType.IsGenericType &&
      conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        if (value == null)
        {
            return null;
        } // end if

        // It's a nullable type, and not null, so that means it can be converted to its underlying type,
        // so overwrite the passed-in conversion type with this underlying type
        System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);

        conversionType = nullableConverter.UnderlyingType;
    } // end if

    // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
    // nullable type), pass the call on to Convert.ChangeType
    return Convert.ChangeType(value, conversionType);
}

#endregion 私有方法(Convert.ChangeType处理Nullable<>和非Nullable<>)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值