0

我知道这个问题已经问了一百万次了。但我的情况,我很奇怪,我不明白。我得到了一个循环引用,下面是我的代码/配置:

  1. 我将 Entity 作为所有实体的基类。

    [DataContract(IsReference = true)]
    public class Entity : IEntity
    
  2. 继承类是这样的,由Entity Framework 6创建

    [DataContract]
    public partial class User: Entity
    

    我有Group, User, GroupUser, GroupAdministrator. 我想这里的名字很清楚。GroupGroupUserUserGroupUserGroupUserGroup & User

  3. 在 DbContext 中,代理创建被关闭,延迟加载被打开。

  4. 错误来自此方法,当我调用它时,我得到一个 cyclic reference.

    public IList<Group> GetGroups()
    {
        return _groupRepository.GetAll(true, _ => _.GroupAdministrators.Select(__=>__.User), _ => _.GroupUsers.Select(__ => __.User));
    }
    

    我调试,根本原因是这样的:_ => _.GroupUsers.Select(__ => __.User)

    _groupRepository.GetAll():_

    public IList<T> GetAll(bool? isActive = true, params Expression<Func<T, object>>[] includes)
    {
        IQueryable<T> query = BrokerageSimulatorContext.Set<T>()
            .Where(_ => (isActive.HasValue && _.IsActive == isActive) || !isActive.HasValue);
        return includes.Aggregate(query, (current, includeProperty) => current.Include(includeProperty)).ToList();
    }
    
  5. 为什么我需要?_ => _.GroupUsers.Select(__ => __.User)因为我需要在列出所有组时包括该组的用户。

4

0 回答 0