문제

나는 사용 중입니다 automapper 다음 클래스의 + ef (entities => poco) :

public class Category
{
    public int CategoryID { get; set; }

    public string Name { get; set; }

    public Category Parent { get; set; }

    public IList<Category> Children { get; set; }
}

이 수업은 그 자체 (부모 / 자녀)와 관계가 있기 때문에 Automapper는 미쳤고 stackoverflow 예외를 던졌습니다. 이 문제를 경험 한 적이 있습니까?

도움이 되었습니까?

해결책

CustomValueresolvers를 만들어 해결했습니다. 해야 할 아름다운 일은 아니지만 효과가 있습니다.

Mapper.CreateMap<Category, CategoryDTO>()
                .ForMember(c => c.Parent, opt => opt.ResolveUsing<ParentResolver>())
                .ForMember(c => c.Children, opt => opt.ResolveUsing<ChildrenResolver>());

Mapper.CreateMap<CategoryDTO, Category>()
                .ForMember(c => c.Parent, opt => opt.ResolveUsing<ParentDTOResolver>())
                .ForMember(c => c.Children, opt => opt.ResolveUsing<ChildrenDTOResolver>());


public class ParentResolver : ValueResolver<Category, CategoryDTO>
    {
        protected override CategoryDTO ResolveCore(Category category)
        {
            CategoryDTO dto = null;

            if (category.Parent != null)
                dto = Mapper.Map<Category, CategoryDTO>(category.Parent);

            return dto;
        }
    }

    public class ParentDTOResolver : ValueResolver<CategoryDTO, Category>
    {
        protected override Category ResolveCore(CategoryDTO category)
        {
            Category poco = null;

            if (category.Parent != null)
                poco = Mapper.Map<CategoryDTO, Category>(category.Parent);

            return poco;
        }
    }

    public class ChildrenResolver : ValueResolver<Category, EntityCollection<CategoryDTO>>
    {
        protected override EntityCollection<CategoryDTO> ResolveCore(Category category)
        {
            EntityCollection<CategoryDTO> dtos = null;

            if (category.Children != null && category.Children.Count > 0)
                dtos = Mapper.Map<IList<Category>, EntityCollection<CategoryDTO>>(category.Children);

            return dtos;
        }
    }

    public class ChildrenDTOResolver : ValueResolver<CategoryDTO, IList<Category>>
    {
        protected override IList<Category> ResolveCore(CategoryDTO category)
        {
            IList<Category> pocos = null;

            if (category.Children != null && category.Children.Count > 0)
                pocos = Mapper.Map<EntityCollection<CategoryDTO>, IList<Category>>(category.Children);

            return pocos;
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top