DataTabletoModelHelper
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace InsiderTrading.Infrastructure.Helpers
{
public static class ModelHelper
{
/// <summary>
///Get DataTable From Model List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public static DataTable GetDataTableFromList<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties by using reflection
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
/// <summary>
/// Convert Single row Datatable To Model
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
///
public static T ConvertDataTableRowToModel<T>(this DataRow row) where T : class, new()
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
if (prop.PropertyType.IsGenericType && prop.PropertyType.Name.Contains("Nullable"))
{
if (!string.IsNullOrEmpty(row[prop.Name].ToString()))
prop.SetValue(obj, Convert.ChangeType(row[prop.Name],
Nullable.GetUnderlyingType(prop.PropertyType), null));
//else do nothing
}
else
prop.SetValue(obj, Convert.ChangeType(row[prop.Name], prop.PropertyType), null);
}
catch
{
continue;
}
}
return obj;
}
/// <summary>
/// Convert Datatable To Model List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
///
public static List<T> ConvertDataTableToModelList<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName.ToLower()).ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row => {
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name.ToLower()))
{
try
{
pro.SetValue(objT, row[pro.Name]);
}
catch (Exception ex) { }
}
}
return objT;
}).ToList();
}
//public static List<T> ConvertDataTableToModelList<T>(DataTable dt)
//{
// List<T> data = new List<T>();
// foreach (DataRow row in dt.Rows)
// {
// T item = GetItem<T>(row);
// data.Add(item);
// }
// return data;
//}
//private static T GetItem<T>(DataRow dr)
//{
// Type temp = typeof(T);
// T obj = Activator.CreateInstance<T>();
// foreach (DataColumn column in dr.Table.Columns)
// {
// foreach (PropertyInfo pro in temp.GetProperties())
// {
// if (pro.Name == column.ColumnName)
// pro.SetValue(obj, dr[column.ColumnName], null);
// else
// continue;
// }
// }
// return obj;
//}
}
}
Comments
Post a Comment