We use EntityFramework 6.2.0 in conjunction with Automapper 6.2.2 to map between entities and DTOs. Unfortunately, with some of these mappings the System.StackOverflowException occurs again and again. After extensive research we have already tried several things to fix the problem:
- Setting MaxDepth (global)
- Setting PreserveReferences (global)
- Enabling/Disabling CreateMissingTypeMaps (global)
- Trying to understand the execution plan
So far nothing fixed the problem. Various articles describe that circular references should be avoided in the DTOs, which unfortunately is NOT the case with us.
Circular reference example:
public class OneDTO
{
public Guid Id { get; set; }
public List<OtherDTO> Others { get; set; }
}
public class OtherDTO
{
public Guid Id { get; set; }
public OneDTO One { get; set; }
}
public class Profiles : Profiles
{
public Profiles()
{
CreateMap<One, OneDTO>().ReverseMap();
CreateMap<Other, OtherDTO>().ReverseMap();
}
}
However, the problem also occurs if these supposed circular reference properties are not set at all, i.e. are NULL. But if you remove these properties completely from the class, the error does not occur any more.
Are there other possible causes besides the circular references? Can this error also occur due to a wrong configuration? In most cases we use such a mapping:
CreateMap<One, OneDTO>().ReverseMap();
The AssertConfigurationIsValid method is full of warnings about "Unmapped members were found.
The main question we ask ourselves is whether we have overlooked a configuration, misconfigured it, or whether we really need to remove all circular references from the DTOs.
As a side note if it is relevant: We use SimpleInjector as a DI container which we use to tie up the MappingConfiguration in a central place and inject it into the required places where exists a dependency on IMapper.