Automapper一对多关系

Automapper one-to-many relationship

我有一个创建课程的方法。该课程保留了教师及其 ID。但是添加Course后,TeacherID有值,Teacher为null。我认为问题出在映射中。 CourseAddRequest只有teacherID,如何添加Teacher?

添加课程:

public CourseResponse AddCourse(CourseAddRequest courseAddRequest, Guid teacherId)
        {
            var teacher = _uniDbContext.Teachers
                .Include(t => t.Courses)
                .SingleOrDefault(t => t.Id == teacherId);

            if (teacher == null)
                throw new Exception("User doesn't exist");

            var course = _mapper.Map<Course>(courseAddRequest);
            teacher.Courses.Add(course);
            _uniDbContext.Teachers.Update(teacher);
            _uniDbContext.Courses.Update(course);
            _uniDbContext.Courses.Add(course);
            _uniDbContext.SaveChanges();
            return _mapper.Map<CourseResponse>(course);
        }

课程:

public class Course : BaseEntity
    {
        public string Header { get; set; }
        public string Description { get; set; }
        public Guid TeacherId { get; set; }
        public Teacher Teacher { get; set; }

        public List<Student> StudentsOnCourse { get; set; } = new List<Student>();
    }

课程响应:

public class CourseResponse
    {
        public Guid Id { get; set; }
        public string Header { get; set; }
        public string Description { get; set; }

        public TeacherResponse Teacher { get; set; }
        public Guid TeacherId { get; set; }
        public IEnumerable<StudentResponse> Students { get; set; }
    }

课程添加请求:

public class CourseAddRequest
    {
        public string Header { get; set; }
        public string Description { get; set; }
        public Guid TeacherId { get; set; }
    }

课程简介:

public class CourseProfile : Profile
    {
        public CourseProfile()
        {
            CreateMap<CourseAddRequest, Course>();
            CreateMap<Course, CourseResponse>();
        }
    }

教师简介:

public class TeacherProfile : Profile
    {
        public TeacherProfile()
        {
            CreateMap<TeacherAddRequest, Teacher>();
            CreateMap<Teacher, TeacherResponse>();
        }
    }

你猜对了。当您执行从 CourseAddRequest 到 Course 的映射时,它没有 Teacher 因此 Course teach 将为空。

var course = _mapper.Map<Course>(courseAddRequest);

假设您正在使用 EntityFramework 或其他 ORM,由于您在课程中通过 TeacherId 属性 引用的教师存在,因此它能够正确插入.

当您在方法的第 11 行将课程添加到教师的课程时,这仍然使教师 属性 在课程中为空。因此,当您将其映射到 CourseResponse 时,您会得到 null。

有两种方法可以解决这个问题,首先,您可以将 teach 添加到您的课程对象,这样映射器会在映射到 return 语句中的 CourseResponse 之前找到教师。

course.Teacher = teacher;

或者将教师对象直接映射到响应。

var courseResponse = _mapper.Map<CourseResponse>(course);
courseResponse.Teacher = _mapper.Map<TeacherResponse>(teacher);
return courseResponse;