我尝试了很多选项让Automapper正确映射父/子关系。
型号:
//Entity
public class WorkArea
{
public Guid Id;
public Name {get;set;}
public Guid? ParentWorkAreaId {get;set;} //for entity Framework Foreign Key
public WorkArea ParentWorkArea {get;set;}
public ICollection<WorkArea> ChildWorkareas {get;set;}
}
//DTO
public class WorkAreaDto
{
public Guid Id;
public Name {get;set;}
public Guid? ParentWorkAreaId {get;set;} //for entity Framework Foreign Key
public WorkAreaDto ParentWorkArea {get;set;}
public ICollection<WorkAreaDto> ChildWorkareas {get;set;}
}
此映射导致堆栈溢出:
Mapper.CreateMap<WorkArea,WorkAreaDto>();
我尝试了与this完全相同的错误
然后我创建了一个自定义TypeConverter,但我不仅要为子节点编写递归方法,还要为父节点编写递归方法。看起来很多工作确实可以正确映射。不确定我是否做错了什么。我正在使用2.0
更新 我认为我的问题是Entity Framework生成的System.Data.Entity.DynamicProxies。
答案 0 :(得分:1)
这对我来说效果很好,也许你应该检查你的数据:
[TestMethod]
public void TestMethod1()
{
Mapper.CreateMap<WorkArea, WorkAreaDto>();
var source = CreateSource();
WorkAreaDto destination = new WorkAreaDto();
Mapper.Map(source, destination);
Assert.AreEqual(destination.ChildWorkareas.Count, 3);
}
private WorkArea CreateSource()
{
var id = Guid.NewGuid();
var result = new WorkArea();
result.Id = id;
result.Name = "Name" + id.ToString();
result.ParentWorkArea = CreateSourceParent(result);
result.ParentWorkAreaId = result.ParentWorkArea.Id;
result.ChildWorkareas = CreateSourceChildren(result);
return result;
}
private ICollection<WorkArea> CreateSourceChildren(WorkArea parent)
{
var result = new Collection<WorkArea>
{
new WorkArea() { Id = Guid.NewGuid(), Name = "Child1", ParentWorkArea = parent, ParentWorkAreaId = parent.Id },
new WorkArea() { Id = Guid.NewGuid(), Name = "Child2", ParentWorkArea = parent, ParentWorkAreaId = parent.Id },
new WorkArea() { Id = Guid.NewGuid(), Name = "Child3", ParentWorkArea = parent, ParentWorkAreaId = parent.Id }
};
return result;
}
private WorkArea CreateSourceParent(WorkArea source)
{
var id = Guid.NewGuid();
var result = new WorkArea();
result.Id = id;
result.Name = "Name" + id.ToString();
result.ChildWorkareas = new Collection<WorkArea>
{
source
};
return result;
}