【发布时间】:2021-08-25 13:29:03
【问题描述】:
我想使用 AutoMapper 将我的模型映射到我的视图模型以显示在视图中,然后再保存回数据库。
我能够成功地将模型映射到除ICollection 数据之外的模型字段。我进行了审查,并且在填充模型时确实得到了 ICollection
以我的模型为例:
public class CarDetails
{
public int Id { get; set; }
public string Make{ get; set; }
[ForeignKey("CarId")]
public int CarId { get; set; }
public Car Car { get; set; }
public int? CarFlag { get; set; }
}
public class Car
{
public ICollection<CarDetails> CarDetails { get; set; }
[Key]
public int Id { get; set; }
public string Name{ get; set; }
}
以我的视图模型为例:
public class CarDetailsVM
{
public string Make{ get; set; }
public int? CarFlag { get; set; }
}
public class CarVM
{
public ICollection<CarDetailsVM> CarDetailsVM{ get; set; }
public string Name{ get; set; }
}
我的映射配置文件:
CreateMap<Car, CarVM>().ReverseMap();
CreateMap<CarDetails, CarDetailsVM>().ReverseMap();
在我的控制器中 - 我得到了信息:
Car model = repo.GetData(1);
var vm = _mapper.Map<CarVM>(model);
当我查看 vm 对象时,我看到除了 CarDetailsVM 集合值之外的所有字段。我检查了模型,发现它正在从 repo.GetData(1) 检索数据
关于如何将ICollection 模型映射到VM ICollection 有什么建议吗?
在提交时我会这样做:这是正确的方式吗?
[HttpPost]
public IActionResult Car(CarVM viewModel)
{
var carObject = repo.GetData(1);
var mappedCar = _mapper.Map<CarVM, Car>(viewModel, carObject);
....//then I would pass mappedCar to repo to save to DB
}
【问题讨论】:
标签: c# asp.net-core-mvc automapper