Home > Net >  Automapper: Conditionally changing value of item in list
Automapper: Conditionally changing value of item in list

Time:09-03

I have a list that I get from a database, I want to map that to another class and get the result. However, one of the items of that list (ContractTitle) has its own properties (ContractTitle.Buyer or ContractTitle.Seller which are strings). For the mapped result, I want to change the value of each ContractTitle to either ContractTitle.Buyer or ContractTitle.Seller.

The example below is what I am attempting to do, I don't really know how to proceed though. I feel I would need a custom resolver to actually achieve this. Sorry, I am very new to automapper, find the documentation a bit confusing. Thanks!

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

CodePudding user response:

Instead of passing the internal data that needs to be mapped into the map operation, it would probably be a better idea to pass in the condition itself, and let the mapper pick one or the other based on it while mapping each member individually:

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);
  • Related