How to using AutoMapper and Entity Framework to Pass a Dynamic Parameter To Select A Child Object And Map

Viewed 27

I've a requirement to map Company to CompanyDTO based on the user domain. I need to pass the Domain ID to the the Mapper and select CompanyDomain object

    public class Company
{
    public int CompanyID { get; set;}
    public int Name { get; set;}
    public List<CompanyDomain> Domains { get; set; }
}

public class CompanyDomain
{
    public int DomainID { get; set; }
    public string Analyst { get; set; }
}

public class CompanyDTO
{
    public int CompanyID { get; set; }
    public string Name { get; set; }
    public string Analyst { get; set; }
}
1 Answers

You can do this by using the mapping options. For example, set up your map like this:

cfg.CreateMap<Company, CompanyDTO>()
    .ForMember(
        d => d.Analyst, 
        opts => opts.MapFrom((s, d, _, ctx) => //Use the 4 parameter version
            s.Domains.Single(d => d.DomainID == (int)ctx.Items["DomainID"]).Analyst));

It looks a little more complicated than it really is, but it's just telling AutoMapper to search the company domains using a parameter that was passed in. You would then use it like this:

var result = mapper.Map<CompanyDTO>(company, opts => opts.Items["DomainID"] = 2);
Related