精易论坛
标题:
第六十六天
[打印本页]
作者:
老郭
时间:
2019-12-18 17:17
标题:
第六十六天
今日学习内容
66.1 通过反射实现表与实体 集合的映射
66.2 通过 AutoMapper 自动实体映射
66.3 ADO.NET 事务处理
今日学习内容
1.自己动手扩展 DateTable 的映射部分
作者:
神女软件定制
时间:
2019-12-18 18:38
Datatable?
作者:
qingshanlushui
时间:
2020-1-18 13:52
/// <summary>
/// DataTable 行转换
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T AdapterToModel<T>(this DataRow dr)
{
Type modelType = typeof(T);
T model = Activator.CreateInstance<T>();
foreach (var col in dr.Table.Columns)
{
PropertyInfo p = modelType.GetProperty(col.ToString(), BindingFlags.GetProperty | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (p != null && IsNotDBNull(dr[col.ToString()]))
{
p.SetValue(model, CheckType(dr[col.ToString()], p.PropertyType));
}
}
return model;
}
/// <summary>
/// DataTable 集合转换...内部调用AdapterToModel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> AdapterToList<T>(this DataTable dt)
{
List<T> list = new List<T>();
DataRowCollection rows = dt.Rows;
foreach (DataRow row in rows)
{
list.Add(AdapterToModel<T>(row));
}
return list;
}
复制代码
作者:
骄傲高冷男神
时间:
2020-2-5 15:02
看帖必回是一种美德
作者:
xuxuand
时间:
2020-2-23 11:08
66666666666666666
作者:
duanyijun
时间:
2020-2-25 10:04
看看再说了
作者:
KaiNan
时间:
2021-1-17 18:15
Adapter
static object CheckType(object value, Type pType)
{
//判断students 是否定义为Nullable
if (pType.IsGenericType && pType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
//如果数据库的值为null,返回null setValue 不会报错
if (value == null || value is DBNull) return null;
//不为null 则通过NullableConverter 把pType转化
NullableConverter nc = new NullableConverter(pType);
pType = nc.UnderlyingType;
}
//一般情况直接调用convert 转化
return Convert.ChangeType(value, pType);
}
public static T ToModelByAdataReader<T>(this IDataAdapter dataAdapter)
{
Type mType = typeof(T);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
DataRowCollection dataRowCollection = dataTable.Rows;
Console.WriteLine(dataRowCollection);
T tInstance = Activator.CreateInstance<T>();
foreach (DataRow item in dataRowCollection)
{
for (int i = 0; i < item.ItemArray.Length; i++)
{
PropertyInfo pinfo = mType.GetProperty(item.Table.Columns[i].ColumnName, BindingFlags.GetProperty | BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
if (pinfo != null)
{
pinfo.SetValue(tInstance, CheckType(item[i], pinfo.PropertyType));
}
}
return tInstance;
}
return default(T);
}
欢迎光临 精易论坛 (https://125.confly.eu.org/)
Powered by Discuz! X3.4