本文介绍了AutoMapper取消展平相同类型的复杂对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在映射以下复杂类型时遇到问题:
I have a problem mapping the following complex types:
RequestDTO
{
int OldUserId;
string OldUsername;
int NewUserId;
string NewUsername;
}
Request
{
User OldUser;
User NewUser;
}
User
{
int UserId;
string Username;
}
将Request
映射/展平到RequestDTO
很容易.但是如何展开该对象?
Mapping/flattening Request
to RequestDTO
is easy. But how to unflatten this object?
推荐答案
假定您将类和字段公开,下面的示例演示如何在AutoMapper中处理此问题.您需要告诉它如何从dto重构复杂类型.
Assuming that you make your classes and fields public, the example below shows how to handle this in AutoMapper. You need to tell it how to reconstruct your complex types from the dto.
Mapper.CreateMap<RequestDTO, Request>()
.ForMember(request => request.OldUser,
mappingOption =>
mappingOption.MapFrom(dto => new User {UserId = dto.OldUserId, Username = dto.OldUsername}))
.ForMember(request => request.NewUser,
opt => opt.MapFrom(dto => new User {UserId = dto.NewUserId, Username = dto.NewUsername}));
这篇关于AutoMapper取消展平相同类型的复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!