如何避免使用AutoMapper进行循环引用? [英] How to avoid circular references with AutoMapper?

查看:335
本文介绍了如何避免使用AutoMapper进行循环引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following models (and corresponding DTOs):

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,对其他对象的引用或对同一对象的引用.

In my scenario, I can have a Link object where FirstLink and/or SecondLink can be null, references to other objects, or references to the same object.

现在,我想使用EF从数据库加载OtherObject实体.我加载了实体本身以及与之关联的Link对象. EF完美地做到了这一点.

Now I want to load an OtherObject entity from the db using EF. I load the entity itself and also the Link object associated with it. This is done perfectly by EF.

在这种特殊情况下,FirstLinkSecondLinkLink相同,因此,从模型到dto的自动映射时,它只会一直映射到遗忘中.

In this particular case, both FirstLink and SecondLink are the same as Link, therefore, when automapping from model to dto it just keeps on mapping into oblivion.

我的映射是:

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

其中Bidirectional()是此扩展名:

where Bidirectional() is this extension:

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

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

Is there way to tell Automapper not to map further down the tree in this case?

推荐答案

我要解决的方法是为孩子创建单独的DTO对象:

The way I would handle this is to create separate DTO objects for the children:

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递归/自引用.在您的结构中明确说明您希望它走多深.

Don't let your DTOs be recursive/self-referential. Be explicit in your structure on how deep you want it to go.

EF无法执行递归联接,您只能执行一个级别,所以不要使您的DTO陷入无限深层次的关系.要明确.

EF can't do recursive joins, you're only doing one level, so don't make your DTOs go nuts with infinitely deep relationships. Be explicit.

这篇关于如何避免使用AutoMapper进行循环引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆