|
发表于 2021-1-17 18:15:47
|
显示全部楼层
缅甸
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);
} |
|