views:

40

answers:

2

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.
+2  A: 

You can use AutoMapper - it's built to do this stuff I think

Preet Sangha
The problem is AutoMapper doesn't map when it cannot determine the type. It sees "object" which doesn't have any properties.
Dr. Zim
+3  A: 

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 });
    }
}
dahlbyk
Delicious Reflection goodness! Or something like that!
Andrew Barber
Fantastic! I had to add some null value checks, but afterward, it worked like a charm. Thanks a lot!
Dr. Zim