Hot to set object values from stored proc parameters?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm trying to iterate stored parameters and populate any public properties of
an object with the parameter value. I've suceeded in doing it the other way
around, but when I try it to the object I keep getting the error "Object does
not match target type".

I've tried field.SetValue(p, p.Value, BindingFlags.SetField, null, null,
null) and a couple variations without sucess.

Thanks in advance for any help you can offer.

public static void PopulateRecordFromProcedureParameters(Object Record,
SqlCommand cmd)
{
PropertyInfo field = null;

foreach (SqlParameter p in cmd.Parameters)
{
if (p.Direction != ParameterDirection.Input)
{
field =
Record.GetType().GetProperty(p.ParameterName.Replace("@", ""));
// Here's where I need to set the value
field.SetValue(p, p.Value, BindingFlags.SetField, null, null, null);
}
}

} // PopulateRecordFromProcedureParameters
 
Hi,

You have to make sure that both p.Value and the target property are of the
same type.

Even more, you need to check if the property has a set member.
 
I realize I have to cast the value from the stored procedure, but I'm not
having any success in doing so. Since I'm trying to match a parameter with
its corresponding property iteratively I can't know the types at design time
so I need to know how to cast a parameter value to the type of an arbitrary
property at runtime. What wold I use in place of (CAST AS field TYPE) to
cast the value of the parameter to the type of the field?

field.SetValue(Record, (CAST AS field TYPE)p.Value, null);
 
Byron said:
I realize I have to cast the value from the stored procedure, but I'm not
having any success in doing so. Since I'm trying to match a parameter
with
its corresponding property iteratively I can't know the types at design
time
so I need to know how to cast a parameter value to the type of an
arbitrary
property at runtime. What wold I use in place of (CAST AS field TYPE) to
cast the value of the parameter to the type of the field?

field.SetValue(Record, (CAST AS field TYPE)p.Value, null);

either TypeDescriptor.GetConverter(p.Value.GetType()).ConvertTo(p.Value,
field.FieldType)
or TypeDescriptor.GetConverter(field.FieldType).ConvertFrom(p.Value)
 
Back
Top