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);
  }