Tag Archives: Automapper Self reference circular error

Automapper Self reference circular error [How to Solve]

Case 1: CodeRule contains List<CodeRuleLine> CodeRuleLines attribute.

CodeRuleDto contains the List<CodeRuleLineDto>CodeRuleLines property.

When CodeRule=>CodeRuleDto, List<CodeRuleLine> cannot directly convert List<CodeRuleLineDto>, so when setting the mapping, it should be

CreateMap<CodeRule, CodeRuleDto>()

.ForMember(dest => dest.CodeRuleLines, opt => opt.MapFrom(src => src.CodeRuleLines));

At the same time, the constructor of CodeRule should be initialized with CodeRuleLines = new List<CodeRuleLine>();.

However, since CodeRuleLine itself has the attribute of CodeRule CodeRule, and CodeRuleLineDto also has the attribute of CodeRuleDto CodeRule, it will report an error of self-reference cycle.

At this time, the mapping in the AutoMapperProfile() method should be changed to CreateMap<CodeRuleLine, CodeRuleLineDto>().ForMember(dest => dest.CodeRule,opt=>opt.Ignore());