Using LINQ to map dynamically (or construct projections)
- by CodeGrue
I know I can map two object types with LINQ using a projection as so:
var destModel = from m in sourceModel
select new DestModelType {A = m.A, C = m.C, E = m.E}
where
class SourceModelType
{
string A {get; set;}
string B {get; set;}
string C {get; set;}
string D {get; set;}
string E {get; set;}
}
class DestModelType
{
string A {get; set;}
string C {get; set;}
string E {get; set;}
}
But what if I want to make something like a generic to do this, where I don't know specifically the two types I am dealing with. So it would walk the "Dest" type and match with the matching "Source" types.. is this possible? Also, to achieve deferred execution, I would want it just to return an IQueryable.
For example:
public IQueryable<TDest> ProjectionMap<TSource, TDest>(IQueryable<TSource> sourceModel)
{
// dynamically build the LINQ projection based on the properties in TDest
// return the IQueryable containing the constructed projection
}
I know this is challenging, but I hope not impossible, because it will save me a bunch of explicit mapping work between models and viewmodels.