unable to convert MySQL date/time value to System.DateTime

lqs0112 2012-02-04 11:20:45
环境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;"

仍然报错,请高手帮忙解答如何处理,谢谢~~
...全文
307 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
stonespace 2012-02-04
  • 打赏
  • 举报
回复
应该用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);
}

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧