使用反射编写 ORM 无法正确转换
所以我正在用 C# 编写一个 ORM,纯粹是为了个人学习。我正在循环访问数据库,其中列名与类的属性匹配。然后,我循环访问类的属性并分配相应的数据库列值,但我遇到了从数据库列转换返回值的问题。
var PropCollection = type.GetProperties();
foreach (PropertyInfo Property in PropCollection)
{
Property.SetValue(_t, DReader[Property.Name].ToString(),null);
}
我收到预期的错误:
“System.String”类型的对象无法转换为类型 'System.Int32'。
其中 DReader 只是一个在循环内返回列值的 SQLDataReader,假设该值是 int,我如何将其转换为这样?
Property.GetType();
正确地知道我需要的类型,但如何使用它来转换 DReader[Property.Name]
?
So I am writing, strictly for personal learning, an ORM in C#. I am looping through a database, where the column names match the properties of a class. I am then looping through the properties of the class and assigning the corresponding database column values but i am running into issues casting the return value from the database column.
var PropCollection = type.GetProperties();
foreach (PropertyInfo Property in PropCollection)
{
Property.SetValue(_t, DReader[Property.Name].ToString(),null);
}
I get the expected error:
Object of type 'System.String' cannot be converted to type
'System.Int32'.
Where DReader is just an SQLDataReader returning a column value inside of a loop, say this value is an int, how do I cast it as such??
Property.GetType();
correctly knows the type I need but how do I use that to cast DReader[Property.Name]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Convert.ChangeType
可以处理所有直接转换。您不应在循环中使用
DReader[Property.Name].ToString()
。删除ToString()
。Convert.ChangeType
can handle all straight conversions.You should not use
DReader[Property.Name].ToString()
in your loop. Remove theToString()
.