【问题标题】:How to avoid circular references with AutoMapper?如何避免使用 AutoMapper 进行循环引用?
【发布时间】:2015-02-28 00:49:27
【问题描述】:

我有以下模型(和相应的 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 可以为空、对其他对象的引用或对同一对象的引用。

现在我想使用 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 不要再往下映射树?

【问题讨论】:

  • 尝试打开查看器的视图状态
  • 一件小事 - 做 ReverseMap 而不是 Bidirectional,它已经内置了。

标签: c# automapper


【解决方案1】:

我的处理方式是为孩子创建单独的 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 因无限深的关系而发疯。明确。

【讨论】:

  • 这让我想起了我最近做的一个项目。我有一个具有一对多关系的非 EF 域对象,我需要将其映射到应用程序级 DTO 并返回到客户端,而不使用 JSON 引用。在域上,我使用长椅上的 mutator 在 setter 上设置对自身的引用。映射没问题,因为 DTO 上不存在 mutator 行为。关系映射正确。客户端序列化程序是我指定递归级别的地方。臭?或者好吧,因为决定深度的合适位置是客户?
  • 我知道我参加聚会有点晚了,但是您能否举个例子说明当 Supervisor 是 ICollection 时如何使用它??
猜你喜欢
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-21
  • 1970-01-01
  • 2015-09-05
相关资源
最近更新 更多