[英]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
中轉換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
表達式是由pred1
和pred2
表達式的相同代碼形成的。
那么,有可能創造pred3
使用pred1
和pred2
避免代碼重復?
您是否嘗試過使用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>();
可能,但是您必須在表達式pred1
和pred2
中調用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.