我在MSSQL数据库中有一个表,其中有大约300列,我只想提取一行并获取列的所有值。我已经使用了这段代码,但是我对GetValue(,)方法有问题。这是我的代码:
private PropertyInfo[] GetValuesDB()
{
......
var result = from val in datacTx.TableA
where val.A == "AA" + "-" + "11" &&
val.B == "CC
select val;
return result.First().GetType().GetProperties();
}
...
public void MethodA()
{
var res = GetValuesDB();
foreach (var propertyInfo in res)
{
var rez = propertyInfo.GetValue(res,null);
}
}我总是得到这样的异常:
Object does not match target type.发布于 2013-08-15 21:10:23
GetValue期望第一个参数的类型是声明属性的类型(或子类型)。
因此,您的result.First()调用返回一个对象的引用-您希望获取该对象的属性……所以这应该是您传递给GetValue的引用。您需要更改代码以返回该引用:
// Ideally, change this to a more appropriate return type...
private object GetValuesDB()
{
......
var result = from val in datacTx.TableA
where val.A == "AA" + "-" + "11" &&
val.B == "CC"
select val;
return result.First();
}
...
public void MethodA()
{
var res = GetValuesDB();
foreach (var propertyInfo in res.GetType().GetProperties())
{
var rez = propertyInfo.GetValue(res, null);
}
}因此,GetValuesDB现在返回对相关实体的引用-然后获取属性描述符,并向每个描述符询问该对象上该属性的值。
https://stackoverflow.com/questions/18253286
复制相似问题