I'm using EntityFramework 6.0, DB first. In my data layer I access my database to get the results.
using(ModelContext m = new ModelContext())
{
var results = m.Person
.Include(p => p.Address)
.Include(p => p.Orders)
.ToList();
responde.Results = results.Select(PersonToDto);
}
Now, the code above is selecting all the columns in the three tables and bringing in way more information than I need and I'm not mapping all of it in the PersonToDto()
method.
So now I'm trying to use a new approach that allows me to select only the columns I want while preserving the mapper.
using(ModelContext m = new ModelContext())
{
var results = m.Person
.Include(p => p.Address)
.Include(p => p.Orders)
.Select(PersonToDtoExpr);
}
public static Expression<Func<Person, PersonDto>> PersonToDtoExpr()
{
return person => new PersonDto
{
Name = person.Name,
Email = person.Email,
Orders = person.Select(p => p.Orders).Select(OrdersToDto)
}
}
This works up to this point, because I have a 1 to * relationship from Person
to Orders
, but when I try to do the same for the Address
I have a problem, I don't have a select statement to use the other Expression
in.
I could do the mapping for the Address
directly on the Person
mapper, but I have around 60 places where I need to map the Address
and I don't want to have to repeat that code everywhere. This would also allow me to basically do the selection of the specific fields I want from the DB while doing the mapping at the same time, segregated in the data layer and reusable in other parts of the code.
Is there a way to map that single object inside of that expression in a way that is usabl in Linq to SQL?
I've been Reading about expression trees, but it's a little too abstract for me to grasp what is happening.