【问题标题】:AutoMapper map ICollection<T> throws an ExceptionAutoMapper 映射 ICollection<T> 抛出异常
【发布时间】:2020-05-24 07:15:29
【问题描述】:

我正在尝试使用 AutoMapper 将我的一个模型映射到它的 DTO,我的模型:

public class Menu : BaseModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int MenuId { get; set; }
    public int? ParentId { get; set; }
    [Required]
    public string Title { get; set; }
    public string Route { get; set; }

    [ForeignKey("ParentId")]
    public virtual Menu Parent { get; set; }
    public virtual ICollection<Menu> Children { get; set; }
}

还有我的 DTO:

public class MenuDTO
{
    public string Title { get; set; }
    public string Route { get; set; }
    public ICollection<MenuDTO> Children { get; set; }
}

我的映射配置文件:

CreateMap<Menu, MenuDTO>().ForMember(dest => dest.Children, opt => opt.MapFrom(src => src.Children));

但在执行时会抛出unsupported mapping exception

Mapping types:
List`1 -> MenuDTO
System.Collections.Generic.List`1[[App.Models.Menu, App, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> App.Models.MenuDTO

那个映射配置出了什么问题?

【问题讨论】:

  • 你有一个无限循环伴侣。你的菜单类有一个菜单列表,每个菜单都有自己的菜单列表……你明白我要去哪里了吗?
  • AM 可以处理递归映射。
  • @Marko 是的,我知道这是一个递归模型,但是如何在 AM 中处理它?
  • @LucianBargaoanu 它究竟是如何处理的?自动地?现在何时/何地停止映射?
  • 我相信一些研究会告诉你如何做。

标签: c# .net-core automapper


【解决方案1】:

也许你的Map 电话看起来像这样:

mapper.Map&lt;MenuDTO&gt;(new[]{new Menu()});

而不是

mapper.Map&lt;List&lt;MenuDTO&gt;&gt;(new[]{new Menu()});

【讨论】:

  • 我的是var menu = _appUserRepository.GetMenu(); // IEnumerable&lt;Menu&gt; var menuDTO = _mapper.Map&lt;MenuDTO&gt;(menu);
  • 不管怎样,看看错误信息,它清楚地说明了问题所在。你的映射对我有用。您发布的代码与您的错误无关。
  • 哦,当 Map 调用为 _mapper.Map&lt;IEnumerable&lt;MenuDTO&gt;&gt;(menu) 而不是 _mapper.Map&lt;MenuDTO&gt;(menu) 时,它可以工作。我认为错误在于 Map 的类型,它应该是 MenuDTOCollection,而不是单个 MenuDTO
  • 显然它必须匹配:)
  • Anw,我的映射配置文件仍然是:CreateMap&lt;Menu, MenuDTO&gt;().ForMember(dest =&gt; dest.Children, opt =&gt; opt.MapFrom(src =&gt; src.Children));。没事吧?
猜你喜欢
  • 2021-11-06
  • 2022-01-04
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
相关资源
最近更新 更多