我的目的地的源地址分散在root dto及其子属性中:
public class Source {
public AccountSource {get;set;}
public string AccountKey {get;set;}
public string AccountPassword {get;set;}
}
public class AccountSource {
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Dest
{
public Account Account { get; set; }
public class Account
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public string Key { get; set; }
}
}
现在我有这样的映射:
CreateMap<Source, Dest>()
.ForPath(x => x.Account.Id, o => o.MapFrom(x => x.Account.Id))
.ForPath(x => x.Account.Name, o => o.MapFrom(x => x.Account.Name))
.ForPath(x => x.Account.Key, o => o.MapFrom(x => x.AccountKey))
.ForPath(x => x.Account.Password, o => o.MapFrom(x => x.AccountPassword));
CreateMap<AccountSource, Dest.Account>()
.ForAllMembers(x => x.Ignore());
但是有一个问题:添加到Dest.Account
的新成员将不被验证。
如果删除ForPath
并离开
CreateMap<Source, Dest>();
CreateMap<AccountSource, Dest.Account>();
未设置密码和密钥,因此我不得不以CreateMap<AccountSource, Dest.Account>().ForMember(x => x.Password, x=> x.Ignore()).ForMember(x => x.Key, x=> x.Ignore())
的方式忽略()它们。
但是随后扁平化无法正常工作(道具完全被忽略,不仅发生在帐户→帐户映射中)。
答案 0 :(得分:1)
默认情况下,ForPath将忽略Dest.Account,但是您始终可以明确地映射它:
CreateMap<Source, Dest>()
.ForPath(d => d.Account.Key, o => o.MapFrom(s => s.AccountKey))
.ForPath(d => d.Account.Password, o => o.MapFrom(s => s.AccountPassword))
.ForMember(d => d.Account, o => o.MapFrom(s => s.Account));
CreateMap<AccountSource, Account>()
.ForMember(d => d.Password, o => o.Ignore())
.ForMember(d => d.Key, o => o.Ignore());
答案 1 :(得分:0)
找到了另一个解决方案:
CreateMap<Source, Dest>()
.ForMember(x => x.Account, o => o.MapFrom(x => x));
CreateMap<Source, Dest.Account>()
.ForMember(x => x.Id, o => o.MapFrom(x => x.AccountSource.Id))
.ForMember(x => x.Name, o => o.MapFrom(x => x.AccountSource.Name))
.ForMember(x => x.Password, o => o.MapFrom(x => x.AccountPassword))
.ForMember(x => x.Key, o => o.MapFrom(x => x.AccountKey));