65.9K
CodeProject is changing. Read more.
Home

Hydrating Objects With Expression Trees - Part II

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Aug 16, 2010

CPOL
viewsIcon

12700

If the intent is to hydrate the objects from data, why not have an expression that does just that?

free hit counters

In my previous post, I showed how to hydrate objects by creating instances and setting properties in those instances.

But, if the intent is to hydrate the objects from data, why not have an expression that does just that? That’s what the member initialization expression is for.

To create such an expression, we need the constructor expression and the property binding expressions:

var properties = objectType.GetProperties();
var bindings = new MemberBinding[properties.Length];
var valuesArrayExpression = Expression.Parameter(typeof(object[]), "v");

for (int p = 0; p < properties.Length; p++)
{
    var property = properties[p];

    bindings[p] = Expression.Bind(
        property,
        Expression.Convert(
            Expression.ArrayAccess(
                valuesArrayExpression,
                Expression.Constant(p, typeof(int))
            ),
            property.PropertyType
        )
    );
}

var memberInitExpression = Expression.MemberInit(
    Expression.New(objectType),
    bindings
);

var objectHidrationExpression = Expression.Lambda<Func<object[], 
		object>>(memberInitExpression, valuesArrayExpression);

var compiledObjectHidrationExpression = objectHidrationExpression.Compile();

This might seem more complex than the previous solution, but using it is a lot more simple:

for (int o = 0; o < objects.Length; o++)
{
    newObjects[o] = compiledObjectHidrationBLOCKED EXPRESSION;
}