如何使用AutoMapper避免循环引用?

Iva*_*ono 4 c# automapper

我有以下模型(和相应的DTO):

public class Link
{
    public int Id {get; set;}
    public int FirstLinkId {get; set;}
    public int SecondLinkId {get; set;}
    public virtual Link FirstLink {get; set;}
    public virtual Link SecondLInk {get; set;}
}

public class OtherObject
{
    public int Id {get; set;}
    public int LinkId {get; set;}
    public string Name {get; set;}
    public virtual Link Link {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

在我的场景中,我可以有一个Link对象,其中FirstLink和/或SecondLink可以为null,对其他对象的引用或对同一对象的引用.

现在我想OtherObject使用EF从数据库加载实体.我加载实体本身以及Link与之关联的对象.这完全由EF完成.

在这个特定的情况下,两个FirstLinkSecondLink是相同的Link,因此,从模型自动映射到DTO它时,只是不断映射被遗忘.

我的映射是:

Mapper.CreateMap<OtherObject, OtherObjectDto>().Bidirectional()
      .ForMember(model => model.LinkId, option => option.Ignore());
Run Code Online (Sandbox Code Playgroud)

其中Bidirectional()是此扩展名:

public static IMappingExpression<TDestination, TSource> Bidirectional<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    return Mapper.CreateMap<TDestination, TSource>();
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,有没有办法告诉Automapper不要在树下进一步映射?

Jim*_*ard 7

我处理这个的方法是为孩子们创建单独的DTO对象:

public class Employee
{
    public int Id {get; set;}
    public string Name { get; set; }
    public Employee Supervisor {get; set; }
}
public class EmployeeDto {
    public int Id {get; set;}
    public string Name { get; set; }
    public SupervisorDto Supervisor { get; set; }

    public class SupervisorDto {
        public int Id {get; set;}
        public string Name { get; set; }
    }
}
Mapper.CreateMap<Employee, EmployeeDto>();
Mapper.CreateMap<Employee, EmployeeDto.SupervisorDto>();
Run Code Online (Sandbox Code Playgroud)

不要让你的DTO递归/自我指涉.在你的结构中明确你想要它有多深.

EF不能做递归连接,你只做一个级别,所以不要让你的DTO与无限深层的关系疯狂.要明确.