【问题标题】:ASP.NET Core MVC : AutoMapper Map ICollectionASP.NET Core MVC:AutoMapper 映射 ICollection
【发布时间】: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


    【解决方案1】:

    由于 Collection 属性的名称在两个模型中不同,因此您需要指定它们。例如,

    CreateMap<Car, CarVM>().ForMember(dest => dest.CarDetailsVM, 
                     opt => opt.MapFrom(src => src.CarDetails))
                    .ReverseMap();
    

    这将确保在使用 Map() 方法时映射集合。

    或者,您可以使用 RecognizePostfixes 方法在 Destination 类型中查找匹配属性时指定要从 Source 中删除的 PostFix。

    public CarProfile()
    {
      RecognizePostfixes("VM");
      CreateMap<Car, CarVM>().ReverseMap();
      CreateMap<CarDetails, CarDetailsVM>().ReverseMap();
    }
    

    Automapper documentation 中阅读有关后缀/前缀配置的更多信息

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多