首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

unable to convert MySQL date/time value to System.DateTime,该怎么解决

2012-04-10 
unable to convert MySQL date/time value to System.DateTime环境VS2010/MySql在数据库中读取DataTable回

unable to convert MySQL date/time value to System.DateTime
环境VS2010/MySql
在数据库中读取DataTable回来,转化为泛型List,数据库字段中有一个bit型和一个datetime型字段。调用如下方法报错:
protected static List<T> ConvertDataTableToList<T>(DataTable dataTable)
{
List<T> list = new List<T>();
Type targetType = typeof(T);
PropertyInfo[] allPropertyArray = targetType.GetProperties();

foreach (DataRow rowElement in dataTable.Rows)
{
T element = Activator.CreateInstance<T>();

foreach (DataColumn columnElement in dataTable.Columns)
{
foreach (PropertyInfo property in allPropertyArray)
{
if (property.Name.Equals(columnElement.ColumnName))
{
if (rowElement[columnElement.ColumnName] == DBNull.Value)
{
property.SetValue(element, null, null);
}
else
{
property.SetValue(element, rowElement[columnElement.ColumnName], null);
}
}
}
}

list.Add(element);
}
return list;
}

报错提示为:unable to convert MySQL date/time value to System.DateTime和
unable to convert System.UInt64 to System.Boolean

在网上搜索解决方案,使用如下数据库连接串:Dim cs as String = "Database=your_db;Data Source=localhost;User Id=root;Password=password;Allow Zero Datetime=True;"

仍然报错,请高手帮忙解答如何处理,谢谢~~

[解决办法]
应该用Convert.ChangeType转换一下,目标类型是PropertyInfo.PropertyType

if (rowElement[columnElement.ColumnName] == DBNull.Value)
 {
 property.SetValue(element, null, null);
 }
 else
 {
 object rTargetValue=Convert.ChangeType(rowElement[columnElement.ColumnName],property.PropertyType);
 property.SetValue(element,rTargetValue , null);
 }

热点排行