using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NX_CommonClassLibrary
{
public static class ColumnToClassPropertyHelper
{
///
/// 数据库表实体类和数据库数据的自动绑定。
///
/// 限定为数据表的实体类
/// 数据表的列集合
/// 数据表的行数据对象
///
public static T ColumnToClassProperty(DataColumnCollection dtCols, DataRow dr) where T : class, new()
{
T tmp = new T();
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo text = cultureInfo.TextInfo;
PropertyInfo[] propertys = tmp.GetType().GetProperties();
foreach (PropertyInfo property in propertys)
{
for (int i = 0; i < dtCols.Count; i++)
{
string colName = dtCols[i].ColumnName;
string toLower = text.ToLower(colName);
string result = text.ToTitleCase(toLower);
result = result.Replace("_","");
if (property.Name == result)
{
if (property.PropertyType.FullName == typeof(DateTime).FullName)
{
property.SetValue(tmp, dr[colName] == DBNull.Value ? new DateTime() : Convert.ToDateTime(dr[colName]), null);
}
else if (property.PropertyType.FullName == typeof(int).FullName)
{
property.SetValue(tmp, dr[colName] == DBNull.Value ? 0 : Convert.ToInt32(dr[colName]), null);
}
else if (property.PropertyType.FullName == typeof(decimal).FullName)
{
property.SetValue(tmp, dr[colName] == DBNull.Value ? 0 : Convert.ToDecimal(dr[colName]), null);
}
else if (property.PropertyType.FullName == typeof(string).FullName)
{
property.SetValue(tmp, dr[colName] == DBNull.Value ? null : dr[colName].ToString(), null);
}
else if (property.PropertyType.FullName == typeof(bool).FullName || property.PropertyType.FullName == typeof(Boolean).FullName)
{
//property.SetValue(tmp, dr[colName] == DBNull.Value ? false : Convert.ToBoolean(dr[colName]), null);
//VS编辑器建议的简化写法。 非常巧妙!!!!!!
property.SetValue(tmp, dr[colName] != DBNull.Value && Convert.ToBoolean(dr[colName]), null);
}
else if (property.PropertyType.BaseType.FullName == typeof(Enum).FullName)
{
#region 旧代码_舍弃不用
// 目前不知道枚举类型应该如何转换值。
// 要求数据库表中凡是枚举列,均使用int类型。而且不允许为null。
// 只有这样才能保证,实体类属性的枚举和数据库表中枚举列的值才能默认转换。
// ToDo:后续研究,枚举类型应该如何自动转换。目标达到:能够囊括所有异常。
//if (dr[colName] == DBNull.Value)
//{
// property.SetValue(tmp, 0, null);
//}
//else
//{
// //property.SetValue(tmp, dr[colName], null);
// property.SetValue(tmp, EnumExtensionHelper.GetEnumObj1(dr[colName] ?? 0), null);
//}
#endregion
property.SetValue(tmp, Enum.Parse(property.PropertyType, (dr[colName] ?? 0).ToString()), null);
}
else
{
property.SetValue(tmp, dr[colName], null);
}
break;
}
}
}
return tmp;
}
}
}