代码优先EF6自引用多对多引发堆栈溢出错误

时间:2016-06-04 22:45:46

标签: c# entity-framework many-to-many stack-overflow self-reference

尝试使用下面的设置查找用户时,我收到了堆栈溢出错误。我已经尝试关闭延迟加载和代理创建,但我仍然收到错误。

public class Authority
{
    public int Id { get; set; }
    public string Domain { get; set; }
    public string Name { get; set; }
    public AuthorityTypeEnum Type { get; set; }
    public virtual List<Authority> Groups { get; set; }
}

on model Creating:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        modelBuilder.Entity<Authority>()
                    .HasMany(a => a.Groups)
                    .WithMany().
                    Map(m =>
                        {
                            m.MapLeftKey("UserId");
                            m.MapRightKey("GroupId");
                            m.ToTable("UsersGroups");
                        }
                    );

        base.OnModelCreating(modelBuilder);
    }

上下文构造函数:

public Context()
{
    this.Configuration.LazyLoadingEnabled = true;
    this.Configuration.ProxyCreationEnabled = true;
}

这是抛出堆栈溢出的代码:

var byUserAndDomain = db.Authorities
                        .FirstOrDefault(a => a.Type == AuthorityTypeEnum.User && a.Domain == MvcApplication.Domain && a.Name == MvcApplication.UserName);

1 个答案:

答案 0 :(得分:0)

我发现了这个问题。虽然使用Linq表达式抛出了错误,但递归发生在外部作用域中。我猜实体框架对我正在使用的对象的递归具有最低容差。