在ASP.NET MVC中创建具有多个模型(实体)的ViewModel时,我使用以下方法:
学生实体:
public class Student
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
//Foreign key for Country
public int CountryId { get; set; }
public virtual Country Country { get; set; }
}
国家实体:
public class Country
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
学生 ViewModel:
public class StudentViewModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
//Foreign key for Country
public int CountryId { get; set; }
public virtual Country Country { get; set; }
}
国家/地区 ViewModel:
public class CountryViewModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
//??? Should I use Student entity or StudentViewModel at here >>>
public virtual ICollection<Student> Students { get; set; }
}
在此阶段,我不确定是否应在ViewModel中添加相关模型的实体或ViewModels。我使用Automapper并映射实体和视图模型,但是我不想映射每个属性,如下所示,并且不想在ViewModel类中合并模型...
CreateMap<Student, StudentViewModel>()
.ForMember(dest => ...)
.ForMember(dest => ...)
.ForMember(dest => ...)
那么,您能否说明一下如何正确合并viewmodel中的多个实体?