Search code examples
c#asp.net-coreentity-framework-coreautomapperfluent

How to map a DTO with a many-to-many relationship to a EF core entity with a relationship table using automapper?


I have two entities in my DB. A and B. I also have a relationship table representing a many to many relation between these entities AB:

public class A
{
    public ICollection<AB> ABs { get; set; }
}

public class B
{
    public ICollection<AB> ABs { get; set; }
}

public class AB
{
    public A A { get; set; }
    public B B { get; set; }
}

Now I want to hide this relation table in my dto like so:

public class ADTO
{
    public ICollection<B> Bs { get; set; }
}

I want a single collection of Bs with my instances represented directly, not as a relation table. I want to have an automapper profile that maps from a list of entities B to a list of previously not existing entities AB with B as an attribute, as well as the instance A itself.

I already have implemented the mapper from A to ADTO like so:

public class AProfile : Profile
{
    public AProfile()
    {
        CreateMap<A, ADTO>()
            .ForMember(dest => dest.B, opt => opt.MapFrom(src => src.AB.Select(y => y.B).ToList()));
        CreateMap<ADTO, A>();
    }
}

What I am missing is the reverse direction: From ADTO with its list of entities to A with its reference to the relationship table entity.


Solution

  • Make your profile like below:

      CreateMap<ADTO, A>()
                .ForMember(dest => dest.AName, opt => opt.MapFrom(src => src.AName))
                .ForMember(dest => dest.ABs, opt => opt.MapFrom(src => src.Bs))
                .AfterMap((src, dest) =>{
                    foreach(var b in dest.ABs)
                    {
                        b.AId = src.Id;
                    }
                });
      CreateMap<B, AB>()
                .ForMember(dest=>dest.BId,opt=>opt.MapFrom(src=>src.Id))
                .ForMember(dest=>dest.B,opt=>opt.MapFrom(src=>src));