2009-08-10 54 views
5

我使用AutoMapper + EF(實體=> POCO)爲下面的類:如何解決AutoMapper錯誤? (計算器除外!)

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異常。你們有沒有遇到過這個問題?

回答

2

我已經通過創建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; 
     } 
    } 
+1

你可以發佈目標類型嗎?我很想解決這個錯誤。 – 2009-08-23 15:38:41

-1