我知道这个问题已经问了一百万次了。但我的情况,我很奇怪,我不明白。我得到了一个循环引用,下面是我的代码/配置:
我将 Entity 作为所有实体的基类。
[DataContract(IsReference = true)] public class Entity : IEntity
继承类是这样的,由Entity Framework 6创建
[DataContract] public partial class User: Entity
我有
Group
,User
,GroupUser
,GroupAdministrator
. 我想这里的名字很清楚。Group
有GroupUser
,User
有GroupUser
,GroupUser
有Group & User
。在 DbContext 中,代理创建被关闭,延迟加载被打开。
错误来自此方法,当我调用它时,我得到一个
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(); }
为什么我需要?
_ => _.GroupUsers.Select(__ => __.User)
因为我需要在列出所有组时包括该组的用户。