I have Parent and Child entities in database. I need to get some of Childs with their parents as ChildBrief and ParentBrief objects respectively that contain only some of fields of the corresponding entities. Thus, ParentBrief and ChildBrief are kind of maps of underlying entities.
I can write:
IQueriable<ChildBrief> result = Childs.Select(x => new ChildBrief
{
Id = x.Id,
Name = x.Name,
Parent = new ParentBrief
{
Id = x.Parent.Id,
Name = x.Parent.Name
}
});
and it will be perfectly compiled into resulting SQL. But i want the ParentBrief mapper to be a separate static function that can be re-used in other places like here and i do the following:
IQueriable<ChildBrief> result = Childs.Select(x => new ChildBrief
{
Id = x.Id,
Name = x.Name,
Parent = mapper.Compile()(x.Parent)
});
private static readonly Expression<Func<Parent, ParentBrief>> mapper =
m => new ParentBrief
{
Id = x.Parent.Id,
Name = x.Parent.Name}
};
EF5 raises an error saying unable to invoke method or something like this (probably at the Compile stage).
Are there any ways to inject simple expressions (just flat mapping) into EF and make them compiled correctly to the SQL? I also want to get IQueryable results with no upfront execution.