如何在另一个表达式中的单个对象上重用一个表达式 [英] How do I reuse an Expression on a single object in another Expression
问题描述
我觉得我缺少一些简单的东西,但是我没有找到可以回答我问题的文档.
I feel like I am missing something simple, but I have not found the documentation that answers my question.
我最近将一些linq投影分解为可重用的表达式.在对集合进行操作时,它的效果很好,但是我似乎无法弄清楚如何将表达式应用于另一个表达式中的单个对象.以下是我要完成的工作的一个示例:
I have recently been decomposing some of the linq projections into reusable expressions. It works great when operating on a collection, but I can't seem to figure out how to apply an expression to a single object in another expression. Below is an example of what I am trying to accomplish:
public class Person
{
public string ID { get; set; }
public string Name { get; set; }
}
public class PersonDto
{
public string ID { get; set; }
public string Name { get; set; }
}
public class Department
{
Person Manager { get; set; }
List<Person> Employees { get; set; }
}
public class DepartmentDto
{
PersonDto Manager { get; set; }
List<PersonDto> Employees { get; set; }
}
public Expression<Func<Person, PersonDto>> CreatePersonDto = p => new PersonDto
{
ID = p.ID,
Name = p.Name
};
public Expression<Func<Department, DepartmentDto>> CreateDepartmentDto = d => new DepartmentDto
{
Manager = d.Manager // How do I transform this `Person` using `CreatePersonDto`
Employees = d.Employees.Select(CreatePersonDto) //Does not work either
};
为了清楚起见,我使用的是Linq-to-Entities,它需要使用此Expression来生成SQL语句.结果,我无法将表达式Compile
表示为Func
,因为我可能可以使用Linq-to-Objects.
To be clear, I am using Linq-to-Entities that needs to use this Expression to generate a SQL statement. As a result, I cannot Compile
the expression to a Func
as I might be able to using Linq-to-Objects.
推荐答案
您可以使用 LINQKit 扩展其他表达式中的表达式:
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();
这篇关于如何在另一个表达式中的单个对象上重用一个表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!