mysql数据反射给实体类_C# DataTable通过反射转实体类

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Text;

namespace MySqlHelper

{

public static class DataTableToModel

{

///

/// DataTable通过反射获取单个像

///

public static T ToSingleModel(this DataTable data) where T : new()

{

try

{

T t = data.GetList(null, true).Single();

return t;

}

catch (Exception e)

{

return new T();

}

}

///

/// DataTable通过反射获取单个像

/// 前缀

/// 是否忽略大小写,默认不区分

///

public static T ToSingleModel(this DataTable data, string prefix, bool ignoreCase = true) where T : new()

{

T t = data.GetList(prefix, ignoreCase).Single();

return t;

}

///

/// DataTable通过反射获取多个对像

///

///

///

///

public static List ToListModel(this DataTable data) where T : new()

{

List t = data.GetList(null, true);

return t;

}

///

/// DataTable通过反射获取多个对像

///

/// 前缀

/// 是否忽略大小写,默认不区分

///

private static List ToListModel(this DataTable data, string prefix, bool ignoreCase = true) where T : new()

{

List t = data.GetList(prefix, ignoreCase);

return t;

}

private static List GetList(this DataTable data, string prefix, bool ignoreCase = true) where T : new()

{

List t = new List();

int columnscount = data.Columns.Count;

if (ignoreCase)

{

for (int i = 0; i < columnscount; i++)

data.Columns[i].ColumnName = data.Columns[i].ColumnName.ToUpper();

}

try

{

var properties = new T().GetType().GetProperties();

var rowscount = data.Rows.Count;

for (int i = 0; i < rowscount; i++)

{

var model = new T();

foreach (var p in properties)

{

var keyName = prefix + p.Name + "";

if (ignoreCase)

keyName = keyName.ToUpper();

for (int j = 0; j < columnscount; j++)

{

if (data.Columns[j].ColumnName == keyName && data.Rows[i][j] != null)

{

string pval = data.Rows[i][j].ToString();

if (!string.IsNullOrEmpty(pval))

{

try

{

// We need to check whether the property is NULLABLE

if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))

{

p.SetValue(model, Convert.ChangeType(data.Rows[i][j], p.PropertyType.GetGenericArguments()[0]), null);

}

else

{

p.SetValue(model, Convert.ChangeType(data.Rows[i][j], p.PropertyType), null);

}

}

catch (Exception x)

{

throw x;

}

}

break;

}

}

}

t.Add(model);

}

}

catch (Exception ex)

{

throw ex;

}

return t;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值