Accepted answer

Can't you just use automapper for that?

public static Expression<Func<TblCustomer, CustomerSummary>> SelectToSummary()
    return m => Mapper.Map<TblCustomer, CustommerSummary>(m);

You'd have to do some bootstrapping, but then it's very reusable.


I may not be getting something, but what it the purpose of this function? If you just want to map one or collection of Tbl object to other objects, why have the expression?

You could just have something like this:

var customers = _customerRepository.GetAll(); // returns IEnumerable<TblCustomer>
var summaries = Mapper.Map<IEnumerable<TblCustomer>, IEnumerable<CustomerSummary>>(customers);

Or is there something I missed?


I don't think you'll be able to use a lambda expression to do this... you'll need to build up the expression tree by hand using the factory methods in Expression. It's unlikely to be pleasant, to be honest.

My generally preferred way of working out how to build up expression trees is to start with a simple example of what you want to do written as a lambda expression, and then decompile it. That should show you how the expression tree is built - although the C# compiler gets to use the metadata associated with properties more easily than we can (we have to use Type.GetProperty).

This is always assuming I've understood you correctly... it's quite possible that I haven't.


How about this:

public static Person CreatePerson(TblPerson data)
    // ...

public static Expression<Func<TblPerson, Person>>  CreatePersonExpression()
    return d => CreatePerson(d);

return m => (new CustomerSummary()
    ID = m.ID,
    CustomerName = m.CustomerName,
    LastSalesContact = CreatePerson(m.LatestPerson)

Related Query

More Query from same tag