Mapping nested classes with Automapper

I have 3 levels of nesting in my project. Something like that:

    public class Assignment
    {
        public Element Element { get; set; }
    }

    public class Element
    {
        public Subject Subject { get; set; }
    }

    public class Subject
    {
        public int? Id { get; set; }

        public string Subject_Title { get; set; }
    }

Each class has many other properties. The database follows the same structure. Now I want to map assignmentfrom the database to view the model.

The mapping I wrote with help automapperworks for the first time, but not after. Thus, the value Subjectis null in subsequent runs, and the Element value in all runs. The problem is only with the topic.

Can someone point me in the right direction and tell me what I'm doing wrong?

        Mapper.CreateMap<db_Subject, Subject>();

        Mapper.CreateMap<db_element, Element>()
              .ForMember(dest => dest.Subject, opt => opt.MapFrom(src => src.db_Subject));

        Mapper.CreateMap<db_assignment, Assignment>()
              .ForMember(dest => dest.Element, opt => opt.MapFrom(src => src.db_element));

, db_subject db_element, db_element db_assignment. .

+4
1

,

, DB .

public class DB_Assignment
{
    public DB_Element Db_Element { get; set; }
}

public class DB_Element
{
    public DB_Subject Db_Subject { get; set; }
}

public class DB_Subject
{
    public int? Db_Id { get; set; }
    public string Db_Subject_Title { get; set; }
}

,

Mapper.CreateMap<DB_Subject, Subject>()
    .ForMember(destination => destination.Id, options => options.MapFrom(source => source.Db_Id))
    .ForMember(destination => destination.Subject_Title, options => options.MapFrom(source => source.Db_Subject_Title))
    .ReverseMap();

Mapper.CreateMap<DB_Element, Element>()
    .ForMember(destination => destination.Subject, options => options.MapFrom(source => source.Db_Subject))
    .ReverseMap();

Mapper.CreateMap<DB_Assignment, Assignment>()
    .ForMember(destination => destination.Element, options => options.MapFrom(source => source.Db_Element))
    .ReverseMap();

,

var db_Assignment_1 = new DB_Assignment { Db_Element = new DB_Element { Db_Subject = null } };
var assignment_1 = MappingEngine.Map<DB_Assignment, Assignment>(db_Assignment_1);

var db_Assignment_2 = new DB_Assignment { Db_Element = new DB_Element { Db_Subject = new DB_Subject { Db_Id = 1, Db_Subject_Title = "Some title" } } };
var assignment_2 = MappingEngine.Map<DB_Assignment, Assignment>(db_Assignment_2);

var db_Assignment_Lst = new List<DB_Assignment> { db_Assignment_1, db_Assignment_2 };
var assignment_Lst = MappingEngine.Map<List<DB_Assignment>, List<Assignment>>(db_Assignment_Lst);

.

+1

Source: https://habr.com/ru/post/1628783/


All Articles