在数据库读取DataTable进行实体转换的时候报错,仔细看数据库的类型是tinyint,null,而实体类中的类型是int?,这时候就会报错
原来出错的代码是这样的:
private static void GetPropertyInfo<T>(DataTable table, Type type, int i, T item) where T : class
{
try
{
PropertyInfo Property;
object RowCol;
foreach (DataColumn column in table.Columns)
{
RowCol = table.Rows[i][column];
Property = type.GetProperty(column.ColumnName);
if ((RowCol != DBNull.Value) && (Property != null))
{
Property.SetValue(item, table.Rows[i][column], null);//这里报错
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
参考过一些文章后,发现在反射的时候内部会进行内部限制,像string转int,byte转nullable都是会报错的。解决方法有以下两种:
1、设置为正确的类型。例如数据库是tinyint,null,那么类的类型应为byte?。推荐此种方法,严格核对格式。
2、在设置值的时候,先进行类型转换,但这个要区分一般的类型和nullable类型,见如下代码。不推荐此方法,虽然可以偷懒,但多一层转换非常影响效率。
public static object ConvertTo(object convertibleValue, Type type)
{
if (!type.IsGenericType)
{
return Convert.ChangeType(convertibleValue, type);
}
else
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(type));
}
}
throw new InvalidCastException(string.Format("Invalid cast from type \"{0}\" to type \"{1}\".", convertibleValue.GetType().FullName, type.FullName));
}
private static void GetPropertyInfo<T>(DataTable table, Type type, int i, T item) where T : class
{
try
{
PropertyInfo Property;
object RowCol;
foreach (DataColumn column in table.Columns)
{
RowCol = table.Rows[i][column];
Property = type.GetProperty(column.ColumnName);
if ((RowCol != DBNull.Value) && (Property != null))
{
Property.SetValue(item, ConvertTo(table.Rows[i][column], Property.PropertyType), null);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
参考:https://www.cnblogs.com/Chavezcn/p/7537211.html
https://q.cnblogs.com/q/3195/
https://blog.csdn.net/xiaohan2826/article/details/8536074