Entity Framework Infinite Self Referencing Entity

.net entity-framework-core


i have 3 table and 3 entity class and table names are Roles,Acls,AclsInRole.

Role entity class has relation with AclsInRole entity

public class RoleEntity : IdentityRole<Guid>, IEntity
public virtual ICollection<AclInRoleEntity> AclRelations { get; } = new List<AclInRoleEntity>();

and Acl entiy has relation with AclsInRole entity

public class AclEntity : BaseEntity
  public virtual ICollection<AclInRoleEntity> RoleRelations { get; } = new List<AclInRoleEntity>();


public class AclInRoleEntity : BaseEntity
        #region Core Properties

        public Guid RoleId { get; set; }

        public virtual RoleEntity Role { get; set; }

        public Guid AclId { get; set; }

        public virtual AclEntity Acl { get; set; }

        #endregion Core Properties

i run code block in the below .this code return the recursive object . for example : RoleEntity -> AclInRoleEntity-> AclEntity -> AclInRoleEntity -> RoleEntity -> AclInRoleEntity -> AclEntity -> AclInRoleEntity -> RoleEntity -> ......

 RoleEntity entity = this._unitOfWork.GetRepository<RoleEntity>().GetFirstOrDefault(
                role => role.Id == new Guid("6FE68340-933C-4F94-64FA-08D68EBA5E79") && role.IsActive, null,
                roles => roles.Include(role => role.AclRelations).ThenInclude(aclRel => aclRel.Acl));

can you help me ? How can solve recursive problem?

2/10/2019 3:29:01 PM

Accepted Answer

The infinite self referencing loop you are facing is called proxy creation while using Eager Loading/Lazy loading in EF/EF Core. You cannot stop this proxy creation while using Eager Loading in EF/EF Core. This is the default behavior of EF/EF core and no way to change this.

But may be (I didn't try out) you can stop the proxy creation for Lazy Loading in EF Core >=2.1 as EF Core documentation said.

But you can stop Self referencing loop due to the proxies while you converting the entity to JSON as follows:

public void ConfigureServices(IServiceCollection services)

            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore


For more details: Related data and serialization

2/11/2019 3:13:53 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow