合并两个转换表达式

时间:2016-02-24 23:12:12

标签: c# .net entity-framework linq expression

方案

一些实体类:

public class BookEntity
{
    public int IdBook { get; set; }
    public string Title { get; set; }
}

public class StudentEntity
{
    public int IdStudent { get; set; }
    public string Name { get; set; }
}

public class LoanEntity
{
    public int IdLoan { get; set; }
    public StudentEntity Student { get; set; }
    public BookEntity Book { get; set; }
}

一些数据传输对象类:

public class BookDTO
{
    public int IdBook { get; set; }
    public string Title { get; set; }
}

public class StudentDTO
{
    public int IdStudent { get; set; }
    public string Name { get; set; }
}

public class LoanDTO
{
    public int IdLoan { get; set; }
    public StudentDTO Student { get; set; }
    public BookDTO Book { get; set; }
}

我已经有了这个表达式(在dto中转换实体):

Expression<Func<BookEntity, BookDTO>> pred1 = e => new BookDTO
{
    IdBook = e.IdBook,
    Title = e.Title
};

Expression<Func<StudentEntity, StudentDTO>> pred2 = e => new StudentDTO
{
    IdStudent = e.IdStudent,
    Name = e.Name
};

目标:
现在我想创建一个在LoanEntity中转换LoanDTO的表达式。类似的东西:

Expression<Func<LoanEntity, LoanDTO>> pred3 = e => new LoanDTO
{
    IdLoan = e.IdLoan,
    Book = new BookDTO
    {
        IdBook = e.Book.IdBook,
        Title = e.Book.Title
    },
    Student = new StudentDTO
    {
        IdStudent = e.Student.IdStudent,
        Name = e.Student.Name
    }
};

问题:

如果您注意到pred3表达式由pred1pred2表达式的相同代码组成。

那么可以使用pred3pred1创建pred2以避免代码重复吗?

2 个答案:

答案 0 :(得分:3)

您是否尝试过使用Install-Package AutoMapper?它是一个完全解决您问题的库。

var config = new MapperConfiguration(cfg => 
{
  cfg.CreateMap<LoanEntity, LoanDTO>();
  cfg.CreateMap<BookEntity, BookDTO>();
  cfg.CreateMap<StudentEntity, StudentDTO>();
});
var mapper = new ExpressionBuilder(config);

Expression<Func<LoanEntity, LoanDTO>> mappingExpression = mapper.CreateMapExpression<LoanEntity, LoanDTO>();

答案 1 :(得分:1)

可以,但您必须在表达式Compile()pred1中调用pred2方法来调用它:

Expression<Func<LoanEntity, LoanDTO>> pred3 = e => new LoanDTO
{
    IdLoan = e.IdLoan,
    Book = pred1.Compile()(e.Book),
    Student = pred2.Compile()(e.Student)
};

但您只能使用Func<,>

Func<BookEntity, BookDTO> pred1 = e => new BookDTO
{
    IdBook = e.IdBook,
    Title = e.Title
};

Func<StudentEntity, StudentDTO> pred2 = e => new StudentDTO
{
    IdStudent = e.IdStudent,
    Name = e.Name
};

然后,您可以像这样使用它:

Func<LoanEntity, LoanDTO> pred3 = e => new LoanDTO
{
    IdLoan = e.IdLoan,
    Book = pred1(e.Book),
    Student = pred2(e.Student)
};