How do I reuse an Expression on a single object in another Expression

后端 未结 2 425
清歌不尽
清歌不尽 2021-01-23 06:42

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

相关标签:
2条回答
  • 2021-01-23 07:01

    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();
    
    0 讨论(0)
  • 2021-01-23 07:15

    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

    0 讨论(0)
提交回复
热议问题