自引用列表映射

时间:2019-02-16 17:12:16

标签: c# automapper

我有一个有关类别和子级的自引用列表。每个类别都有一个子类别的列表,但自动映射器仅适用于模型的第一级。

CreateMap<Category, CategoryForReturnDto> ()
    .ForMember (dest => dest.ItemsCount, opt => {
        int number = 0;
        opt.ResolveUsing (src => {
            return RecursiveItemsCount (src, number);
        });
    })
    .ForMember (dest => dest.Children, opt => { });
public class Category 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public virtual Category Parent { get; set; }
    public virtual ICollection<Category> Children { get; set; }
    public ICollection<Item> Items { get; set; }
}

public class CategoryForReturnDto
{
     public string Name { get; set; }
     public int Id { get; set; }
     public int ItemsCount { get; set; }
     public ICollection<Category> Children { get; set; }
     public int ParentId { get; set; }
}

1 个答案:

答案 0 :(得分:1)

解决方法是在自动映射器配置文件中拥有

        CreateMap<Category, CategoryForReturnDto> ()
            .ForMember (dest => dest.ItemsCount, opt => {
                int number = 0;
                opt.ResolveUsing (src => {
                    return RecursiveItemsCount (src, number);
                });
            });

和dto内

public class CategoryForReturnDto
{
     public string Name { get; set; }
     public int Id { get; set; }
     public int ItemsCount { get; set; }
     public ICollection<CategoryForReturnDto> Children { get; set; }
     public int? ParentId { get; set; }
}