簡體   English   中英

合並兩個轉換表達式

[英]Combine two Convert Expressions

場景

一些實體類:

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

目標:
現在,我想創建一個在LoanDTO中轉換LoanEntityLoanDTO 就像是:

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表達式的相同代碼形成的。

那么,有可能創造pred3使用pred1pred2避免代碼重復?

您是否嘗試過使用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>();

可能,但是您必須在表達式pred1pred2中調用Compile()方法來調用它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM