有没有办法使用Automapper进行映射

时间:2018-12-28 00:15:04

标签: c#

即使使用自动映射器将TeacherSubjects映射到TeacherVMSubjectVM中的TeacherSubject列表也始终显示为空。

我已经尝试使用自动映射器配置下面的代码。 SchoolName正在发展,但TeacherSubjectlist始终为空。

public class Teacher 
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
    public string Address { get; set; }
    public School WorkingSchool { get; set; }
    public int SchoolId { get; set; }
    public List<TeacherSubject> TeacherSubjectslist { get; set; }
}

public class TeacherSubject
{
    public int TeacherSubjectId { get; set; }
    public Subject Subject { get; set; }
    public int SubjectId { get; set; }
    public Teacher Teacher { get; set; }
    public int TeacherId { get; set; }
}

public class TeacherVM
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
    public string Address { get; set; }        
    public int SchoolId { get; set; }
    public string SchoolName { get; set; }
    public List<SubjectVM> TeacherSubjects { get; set; } 
}

public class SubjectVM
{
    public string SubjectName { get; set; }
    public int SubjectId { get; set; }
}


CreateMap<domain.TeacherSubject, SubjectVM>()
        .ForMember(dest => dest.SubjectName, opt => opt.MapFrom(src => 
src.Subject.SubjectName))
        .ForMember(dest => dest.SubjectId, opt => opt.MapFrom(src => 
src.Subject.SubjectId));
        CreateMap<domain.Teacher, TeacherVM>()
            .ForMember(dest => dest.SchoolName, opt => opt.MapFrom(src => 
src.WorkingSchool.SchoolName))
            .ForMember(dest => dest.TeacherSubjects, opt => opt.MapFrom(src 
=> src.TeacherSubjectslist));

TeacherSubjectlist应该是the SubjectIdSubjectName属性的列表。

1 个答案:

答案 0 :(得分:2)

问题是您在每个包含对象列表的类中都缺少创建列表类型的实例。

您需要做的是在类构造函数中添加列表类型的实例。

未经测试,例如:

public Teacher() 
{
    TeacherSubjectslist = new List<TeacherSubject>();
..
..

相同的概念对具有对象列表的其余类有效。