I feel like I am missing something simple, but I have not found the documentation that answers my question.
I have recently been decomposing some of the linq projection
You can use LINQKit to expand the expressions that you have within other expressions:
private static Expression<Func<Department, DepartmentDto>> CreateDepartmentDtoUnexpanded = d => new DepartmentDto
{
Manager = CreatePersonDto.Invoke(d.Manager),
Employees = d.Employees.Select(employee => CreatePersonDto.Invoke(employee))
.ToList(),
};
public static Expression<Func<Department, DepartmentDto>> CreateDepartmentDto = CreateDepartmentDtoUnexpanded.Expand();
You can:
public static Expression<Func<Department, DepartmentDto>> CreateDepartmentDto = d =>
new DepartmentDto
{
Manager = CreatePersonDto.Compile()(d.Manager),
Employees = d.Employees.Select(CreatePersonDto.Compile()).ToList() // Or declare Employees as IEnumerable and avoid ToList conversion
};
Clearly, instead of calling two times Compile
method you can store the compiled Func