dpv
dpv

Reputation: 157

GetValue of a property

I have a table in an MSSQL database with ~300 columns and I want to extract only one row and get all the values of the columns. I've used this code but I have problems with GetValue(,) method. This is my code:

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

I always obtain this kind of exception:

Object does not match target type.

Upvotes: 3

Views: 273

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502606

GetValue expects the type of the first argument to be the type declaring the property (or a subtype).

So your result.First() call returns a reference to an object - and you want to get the properties on that object... so that should be the reference you pass to GetValue. You'll need to change your code to return that reference:

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

So GetValuesDB now returns a reference to the relevant entity - and then you fetch the property descriptors, and ask each descriptor for the value of that property on that object.

Upvotes: 3

Related Questions