I am using AutoMapper + EF (Entities => POCO) for the following class:
public class Category
{
public int CategoryID { get; set; }
public string Name { get; set; }
public Category Parent { get; set; }
public IList<Category> Children { get; set; }
}
Since this class has relationship with itself (Parent / Children), AutoMapper went crazy and threw a Stackoverflow exception. Have ever any of you experienced this problem?
I've resolved it by creating CustomValueResolvers. It is not the beautiful thing to do, but it is working.
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;
}
}
This appears to be a known problem. Automapper goes in an infinate loop.
Here is a link to someone who managed to get around this problem:
http://blogs.ugidotnet.org/lmauri/archive/2009/05/02/automapper-efpocogenerator-entityframework-and-associations.aspx
Add here is a link to the translated version of this page :)
http://translate.google.com/translate?hl=en&sl=it&u=http://blogs.ugidotnet.org/lmauri/archive/2009/05/02/automapper-efpocogenerator-entityframework-and-associations.aspx&ei=UneASvahFoPe-Qa_38RU&sa=X&oi=translate&resnum=2&ct=result&prev=/search%3Fq%3Dstackoverflow%2Bautomapper%26hl%3Den%26sa%3DN%26start%3D20