自动映射程序:有条件地更改列表中项的值



我有一个从数据库中获得的列表,我想将其映射到另一个类并获得结果。然而,该列表中的一个项(ContractTitle(具有其自己的属性(作为字符串的ContractTitle.BuyerContractTitle.Seller(。对于映射的结果,我想将每个ContractTitle的值更改为ContractTitle.BuyerContractTitle.Seller

下面的例子是我试图做的,但我真的不知道如何继续。我觉得我需要一个自定义的解析器来实现这一点。对不起,我对automapper很陌生,觉得文档有点混乱。谢谢

IEnumerable < Document > document; //=some data from db
var condition = true
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap < Document, Contract > ()
.ForMember(dest => dest.ContractTitle, opt => opt
.MapFrom((src, dest, destMember, context) => context
.Options.Items["ContractTitle"]))
.ForMember(dest => dest.ContractTemplateId, opt => opt
.MapFrom(x => x.DocumentTemplateId))
.ForMember(dest => dest.Id, opt => opt
.MapFrom(x => x.Id)));
configuration.AssertConfigurationIsValid();
IMapper mapper = configuration.CreateMapper();
if (condition) {
return mapper.Map < IEnumerable < Contract >> (document, opt => opt
.Items["ContractTitle"] = document.ContractTitle.Buyer);
} else {
return mapper.Map < IEnumerable < Contract >> (document, opt => opt
.Items["ContractTitle"] = document.ContractTitle.Seller);
}

与其将需要映射的内部数据传递到映射操作中,不如传递条件本身,让映射器在单独映射每个成员时根据它选择一个或另一个:

IEnumerable < Document > document; //=some data from db
var condition = true
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap<Document, Contract>()
.ForMember(dest => dest.ContractTitle, opt => opt
.MapFrom((src, dest, destMember, context) => 
((bool)context.Options.Items["Condition"])
? src.ContractTitle.Buyer
: src.ContractTitle.Seller))
.ForMember(dest => dest.ContractTemplateId, opt => opt
.MapFrom(x => x.DocumentTemplateId))
.ForMember(dest => dest.Id, opt => opt
.MapFrom(x => x.Id)));
configuration.AssertConfigurationIsValid();
IMapper mapper = configuration.CreateMapper();
return mapper.Map<IEnumerable<Contract>> (document, opt => opt
.Items["Condition"] = condition);

相关内容

最新更新