Search code examples
c#automapper-3

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. 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. First, throw same error: 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);

How can I get the Event data with children without circular loop?


Solution

  • You need to disable proxy creation in DbContext as below:

      DbContext.Configuration.ProxyCreationEnabled = false;
    

    And use "Include" lambda expression in your repository

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