AutoMapper 映射 ICollection<T> 抛出异常

AutoMapper map ICollection<T> throws an Exception

我正在尝试使用 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

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

也许您的 Map 调用如下所示:

mapper.Map<MenuDTO>(new[]{new Menu()});

而不是

mapper.Map<List<MenuDTO>>(new[]{new Menu()});