我有一个看起来像这样的StudentClassViewModel:
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SchoolName { get; set; }
public int ClassId { get; set; }
public string ClassName{ get; set; }
public string ClassSubject { get; set; }
前4个属性来自学生表,后3个来自CLass表。我正在使用AutoMapper进行映射,我希望了解如何从ViewModel映射到两个表,理论是VM将数据从View返回到Controller,我想将其从VM映射到2个单独的保存表。
我认为它应该在'CreateMap'配置中,例如:
Mapper.CreateMap<StudentClassViewModel, Student>()
.ForMember(x => x.ClassId, y => y.Some how map to the Class table)
.ForMember(x => x.ClassName, y => y.Some how map to the Class table)
.ForMember(x => x.ClassSubject, y => y.Some how map to the Class table));
我也完全错过了自动映射的意义,无论哪种方式,请告诉我。
答案 0 :(得分:3)
如果您可以控制目标对象,那么可以将Class属性添加到Student类,让AutoMapper为您处理映射:
public class StudentClassViewModel
{
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SchoolName { get; set; }
public int ClassId { get; set; }
public string ClassName { get; set; }
public string ClassSubject { get; set; }
}
public class Class
{
public int Id { get; set; }
public string Name { get; set; }
public string Subject { get; set; }
}
public class Student
{
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SchoolName { get; set; }
public Class Class { get; set; }
}
Mapper.CreateMap<StudentClassViewModel, Student>();
var student = AutoMapper.Mapper.Map<StudentClassViewModel>(viewModel);
答案 1 :(得分:0)
如果这两个表完全分开,则没有简单的方法。 但是,如果学生和班级之间存在关系,就像学生参加班级一样:
public class Class
{
public long Id {get; set;}
public string Name {get; set;}
public string Subject {get; set;}
}
public class Student
{
public string FullName {get; set;}
public Class Class {get; set;}
}
您可以映射如下:
Mapper.CreateMap<StudentClassViewModel, Student>()
.ForMember(x => x.ClassId, y => y.Student.Class.Id)
.ForMember(x => x.ClassName, y => y.Student.Class.Name)
.ForMember(x => x.ClassSubject, y => y.Student.Class.Subject));