自动映射导致堆栈溢出

时间:2014-12-14 18:30:54

标签: c# .net automapper

我使用Automapper来映射两个类:

public partial class db_MyObject
{        
    public int Id { get; set; }
    public Nullable<int> ParentId { get; set; }
}

public class MyObject
{        
    public int Id { get; set; }
    public MyObject Parent { get; set; } // Parent can be null
}

如何配置此映射。我试过这个:

Mapper.CreateMap<db_MyObject, MyObject>()
      .ForMember(dest => dest.Parent, opt => opt.ResolveUsing(model => new db_MyObject() { 
           Id = model.ParentId ?? 0 }));

它导致堆栈溢出。

1 个答案:

答案 0 :(得分:1)

不应该是

Mapper.CreateMap<db_MyObject, MyObject>()
    .ForMember(
        dest => dest.Parent,
        opt => opt.ResolveUsing(model => new MyObject() { 
            Id = model.ParentId ?? 0 })
    );

即。 new MyObject()代替new db_MyObject(),因为ParentMyObject