c# - 如何使用 AutoMapper 避免循环引用?

标签 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;}
}

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

现在我想使用 EF 从数据库中加载一个 OtherObject 实体。我加载实体本身以及与其关联的 Link 对象。 EF 完美地完成了这一点。

在这种特殊情况下,FirstLinkSecondLink 都与 Link 相同,因此,当从模型自动映射到 dto 时,它只是保持关于映射到遗忘。

我的映射是:

Mapper.CreateMap<OtherObject, OtherObjectDto>().Bidirectional()
      .ForMember(model => model.LinkId, option => option.Ignore());

其中 Bidirectional() 是这个扩展:

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

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

最佳答案

我处理这个问题的方法是为 child 创建单独的 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>();

不要让您的 DTO 是递归的/自引用的。在您的结构中明确说明您希望它深入到什么程度。

EF 无法执行递归连接,您只能执行一个级别,因此不要让您的 DTO 因无限深的关系而发疯。明确。

关于c# - 如何使用 AutoMapper 避免循环引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28763042/

相关文章:

c# - 降低字符串时解析枚举

c# - 具有嵌套子列表的自动映射器

c# - 经纬度列表计算中心点与实际略有不同

c# - WPF:如果为 Null,则更改 DataContext?

c# - Application.Current.Shutdown() 没有杀死我的应用程序

c# - 如何使用 System.Drawing 绘制表格

NHibernate、AutoMapper 和 ASP.NET MVC

c# - 如何使用 EntityFramework 5 在导航属性上只深入一层?

c# - 从字符串到 bool 值的奇怪映射行为

c# - 带有 Automapper 的 EF Core 抛出异常 'Entity type cannot be tracked'