You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

87 lines
3.3 KiB

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace Common.Helper
{
public static class Mapper
{
public static IList<T> DataTableToClass<T>(DataTable Table) where T : class, new()
{
var dataList = new List<T>(Table.Rows.Count);
Type classType = typeof(T);
IList<PropertyInfo> propertyList = classType.GetProperties();
if (propertyList.Count == 0)
return new List<T>();
List<string> columnNames = Table.Columns.Cast<DataColumn>().Select(column => column.ColumnName.ToLower()).ToList();
try
{
foreach (DataRow dataRow in Table.AsEnumerable().ToList())
{
var classObject = new T();
foreach (PropertyInfo property in propertyList)
{
if (property != null && property.CanWrite)
{
if (columnNames.Contains(property.Name.ToLower()))
{
if (dataRow[property.Name] != System.DBNull.Value)
{
object propertyValue = System.Convert.ChangeType(
dataRow[property.Name],
property.PropertyType
);
property.SetValue(classObject, propertyValue, null);
}
}
}
}
dataList.Add(classObject);
}
return dataList;
}
catch
{
return new List<T>();
}
}
public static T DataRowToClass<T>(DataRow row) where T : class, new()
{
Type classType = typeof(T);
IList<PropertyInfo> propertyList = classType.GetProperties();
if (propertyList.Count == 0)
return new T();
List<string> columnNames = row.Table.Columns.Cast<DataColumn>().Select(column => column.ColumnName.ToLower()).ToList();
try
{
var classObject = new T();
foreach (PropertyInfo property in propertyList)
{
if (property != null && property.CanWrite)
{
if (columnNames.Contains(property.Name.ToLower()))
{
if (row[property.Name] != System.DBNull.Value)
{
object propertyValue = System.Convert.ChangeType(
row[property.Name],
property.PropertyType
);
property.SetValue(classObject, propertyValue, null);
}
}
}
}
return classObject;
}
catch
{
return new T();
}
}
}
}