实体框架无限的自引用实体

时间:2019-02-10 15:29:01

标签: .net entity-framework-core

我有3个表和3个实体类,表名分别是Roles,Acls,AclsInRole。

角色实体类与AclsInRole实体有关系

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

Acl entiy与AclsInRole实体有关系

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
    }

我在下面运行代码块。此代码返回递归对象。 例如: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));

你能帮我吗?如何解决递归问题?

1 个答案:

答案 0 :(得分:1)

在EF / EF Core中使用急切加载/延迟加载时,遇到的无限自我引用循环称为proxy creation。在EF / EF Core中使用“急切加载”时,无法停止此代理的创建。这是EF / EF核心的默认行为,无法更改。

但是也许(我没有尝试过),您可以按照EF Core documentation所述在EF Core> = 2.1中停止延迟加载的代理创建。

但是由于将实体转换为JSON时,由于代理的原因,您可以停止自我引用循环:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}

有关更多详细信息:Related data and serialization

相关问题