AutoMapper many to many relationship into collection

Viewed 6672

I'm trying to map entities into a collection through a many to many table using AutoMapper.

My domain model (Entity Framework) looks like this:

public class User
{
    public int UserID { get; set; }
    public string Name { get; set; }        
    public IList<UserCompany> UserCompanies { get; set; }
}

public class Company
{
    public int CompanyID { get; set; }
    public string Name { get; set; }
}

public class UserCompany
{
    public int UserCompanyID { get; set; }
    public int UserID { get; set; }
    public int CompanyID { get; set; }
}

I'm trying to map to a class that looks like this:

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

public class UserDTO
{
    public int UserID { get; set; }
    public string Name { get; set; }
    public IList<CompanyDTO> Companies { get; set; }
}

My current mapping configuration looks like this:

Mapper.CreateMap<Company, CompanyDTO>(); //works no problem

Mapper.CreateMap<User, UserDTO>()
    .ForMember( dto => dto.Companies,
    opt => opt.MapFrom(x => Mapper.Map<IList<Company>, IList<CompanyDTO>>(x.UserCompanies.Select( y => y.Company ).ToList())));

Asserting that the configuration is valid returns true, but when I try to actually map a User to a UserDTO, I get: Signature of the body and declaration in a method implementation do not match.

If I use AfterMap and manually move over each Company into the Companies list, it will work, but it seems like I should be able to handle this within create map.

In my query to get a single user from the DB I am including the UserCompany.Company navigation property and I can quickwatch and see that there is being returned.

1 Answers
Related