Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c# - 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.

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
};

EDIT: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...