Using Entity Framework 6, I have display functions between Model objects and viewmodel objects contained in such a class:
public class DataMappers
{
public static Expression<Func<Data.Models.Employer, EmployerViewModel>> EmployerMapper = (e => new EmployerViewModel()
{
Name = e.Name,
Location = e.Location
....
});
}
What can I then call in several places:
results = db.Employers.OrderBy(e => e.Name)
.Select(DataMappers.EmployerMapper)
.ToList();
Which will generate the SQL statement only with the columns that I need. My question is, is there anyway to reuse this if other tables link to my Employer table? i.e.
public static Expression<Func<Data.Models.Person, PersonViewModel>> Person = (p => new PersonViewModel()
{
FirstName = p.FirstName,
LastName = p.LastName,
Employer = *use the 'EmployerMapper' expression above on p.Employer*
....
});
Can this be done, or will I need to duplicate this display code in every situation like this?
I tried to use it only as Funcinstead of Expression<Func>in this second example, which would compile ( Employer = EmployerMapper(p.Employer)), however at runtime you get an exception The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.