using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace WisdomFish.Entity
{
public class ModelBase
{
static T Load<T>(DataRow dataRow)
{
if (dataRow == null)
{
throw new ArgumentNullException("dataRow");
}
Type modelType = typeof(T);
T model = (T)modelType.GetConstructor(Type.EmptyTypes).Invoke(null);
PropertyInfo[] propInfos = modelType.GetProperties();
foreach (PropertyInfo propInfo in propInfos)
{
object value = null;
if (dataRow.Table.Columns.Contains(propInfo.Name))
{
value = dataRow[propInfo.Name];
}
if (value != System.DBNull.Value && value != null)
{
if (propInfo.PropertyType.Name == value.GetType().Name)
{
propInfo.SetValue(model, value, null);
}
else if (propInfo.PropertyType.Name == "Int64")
{
propInfo.SetValue(model,Int64.Parse(value.ToString()), null);
}
else if (propInfo.PropertyType.Name == "Decimal")
{
propInfo.SetValue(model,decimal.Parse(value.ToString()),null);
}
else if (propInfo.PropertyType.Name == "String" && (value.GetType().Name == "Int64" || value.GetType().Name == "Int32" || value.GetType().Name == "Decimal"))
{
propInfo.SetValue(model, value.ToString(), null);
}
else
{
propInfo.SetValue(model, value, null);
}
}
}
return model;
}
public static List<T> Load<T>(DataTable table)
{
if (table == null)
{
throw new ArgumentNullException("table");
}
List<T> list = new List<T>(table.Rows.Count);
foreach (DataRow row in table.Rows)
{
list.Add(Load<T>(row));
}
return list;
}
}
}