我尝试了许多选项来让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>();
我尝试了完全类似的东西,但出现了相同的错误
然后我创建了一个自定义的TypeConverter,但我不仅要为孩子编写递归方法,还要为家长编写递归方法。似乎需要做很多工作才能正确地绘制地图。不确定我是否做错了什么。我正在使用2.0
更新:我认为我的问题是实体框架生成的System.Data.Entity.DynamicProxies。
这对我来说非常好,也许你应该检查一下你的数据:
[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;
}