I have a well known POCO class of Customer to return from my method. However, I only populate properties specified by an ever changing Expression p => new {p.id, p.name} for example, as a parameter to the method.
Somehow I need to copy all matching fields between these two objects.
var returnObject = IList<Customer>();
var partialFieldObject = DC.Customers.Select( expParameter); // wont know the fields
foreach( var partialRecord in partialFieldObject)
{ foreach (var property in partialRecord // Pseudo code)
{
returnObject[property] = property.value; // More Pseudo code
}
}
End result is a strongly typed Customer POCO returned that only has the selected fields populated with values.
Some simple reflection does the trick, assuming the properties on partialFieldObject
line up exactly (case-sensitive) with properties on Customer
...
void SetProperties(object source, object target)
{
var customerType = target.GetType();
foreach (var prop in source.GetType().GetProperties())
{
var propGetter = prop.GetGetMethod();
var propSetter = customerType.GetProperty(prop.Name).GetSetMethod();
var valueToSet = propGetter.Invoke(source, null);
propSetter.Invoke(target, new[] { valueToSet });
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With