我在以下课程中使用AutoMapper + EF(实体=> 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异常。你有没有遇到过这个问题?
答案 0 :(得分:2)
我通过创建自定义值解析器解决了这个问题。这不是美好的事情,但它正在发挥作用。
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 :(得分:-1)
这似乎是一个已知问题。 Automapper进入了一个无限循环。
以下是设法解决此问题的人的链接:
这里添加的是此页面翻译版本的链接:)