简体   繁体   English

Automapper父子自引用循环

[英]Automapper parent-child self referencing loop

I'm trying to map a list model object with a child that has reference to the parent. 我正在尝试使用具有对父级引用的子级来映射列表模型对象。 The Json serialization throws a "Self referencing loop detected" error message. Json序列化将引发“检测到自引用循环”错误消息。 My model classes: 我的模型课:

public class Event
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<EventElement> EventElements { get; set; }
    ...
}

public class EventElement
{
    public int Id { get; set; }
    ...
    public int EventId { get; set; }
    public virtual Event Event { get; set; }
}

I had tried some tricks in Automapper configuration. 我在Automapper配置中尝试了一些技巧。 First, throw same error: Mapper.CreateMap() .ForMember(vm => vm.EventElements, opt => opt.MapFrom(src => src.EventElements)); 首先,抛出相同的错误:Mapper.CreateMap().ForMember(vm => vm.EventElements,opt => opt.MapFrom(src => src.EventElements));

Second, return null for each object in the list: Mapper.CreateMap().MaxDepth(1); 其次,为列表中的每个对象返回null:Mapper.CreateMap()。MaxDepth(1);。

How can I get the Event data with children without circular loop? 如何在没有循环的情况下获取带有子项的事件数据?

You need to disable proxy creation in DbContext as below: 您需要按如下所示在DbContext中禁用代理创建:

  DbContext.Configuration.ProxyCreationEnabled = false;

And use "Include" lambda expression in your repository 并在存储库中使用“包含” lambda表达式

public IQueryable<Customer> GetAllCustomers()
    {
        return DbSet.AsQueryable().Include(s => s.StatusType).Include(s => s.CustomerCategory);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM