Drompai
Drompai

Reputation: 214

How to map (using AutoMapper) a list in a many to many entity

I want to map ProjectDto object to Project object.

So, ProjectDto class contains list of styles:

public class ProjectDto
{
    public List<StyleDto>? Styles { get; set; }
    // and other properties...
}

And it's a Project class:

public class Project
{
    public virtual IEnumerable<StyleOfProject> StylesOfProject { get; set; }
    // and other properties...
}

There is many-to-many relationship between Style and Project, which is represented in StyleOfProject class:

public class StyleOfProject
{
    public int ProjectId { get; set; }
    public virtual Project Project { get; set; }
    
    public int StyleId { get; set; }
    public virtual Style Style { get; set; }
}

public class Style
{
    public virtual IEnumerable<StyleOfProject> StyleOfProjects { get; set; }
    // and other properties...
}

So, I tried to map like this:

CreateMap<ProjectDto, Project>().ForMember(dest => dest.StylesOfProject, opt => opt.MapFrom(src => src.Styles))

And I got empty StylesOfProject. I understand this is incorrect mapping way, but I don't have any right ideas how to map it.

Upvotes: 2

Views: 2075

Answers (1)

Drompai
Drompai

Reputation: 214

So, I found a solution to my problem:

CreateMap<ProjectDto, Project>()
    .ForMember(dest => dest.StylesOfProject,
        opt => opt.MapFrom(src => src.Styles))
    .AfterMap((_, dest) =>
    {
        foreach (var s in dest.StylesOfProject)
        {
            s.ProjectId = dest.Id;
            s.Project = dest;
        }
    });

CreateMap<StyleDto, StyleOfProject>()
    .ForMember(dest => dest.Style,
        opt => opt.MapFrom(src => src))
    .AfterMap((_, dest) =>
    {
        dest.StyleId = dest.Style.Id;
    });

CreateMap<StyleDto, Style>();

AfterMap() is very useful thing in AutoMapper. You can find more information on this website.

Upvotes: 1

Related Questions