You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF7中ICollection关联实体重复加载问题求助

EF Core 5升级到EF Core 7后多对多关联数据重复加载问题

我有Department和Function两个实体,通过中间表DepartmentFunction构成多对多关系,实体类定义如下:

Department 实体类

public class Department 
{
    public Department()
    {
        DepartmentFunctions = new HashSet<DepartmentFunction>();
        PersonFunctions = new HashSet<PersonFunction>();
    }

    public int Id { get; set; }
    
    public string Name { get; set; }
    
    public virtual ICollection<DepartmentFunction> DepartmentFunctions { get; set; }
    
    public DateTime? DeletedAt { get; set; }
}

Function 实体类

public class Function
{
    public Function()
    {
        DepartmentFunctions = new HashSet<DepartmentFunction>();
        FunctionTaskProfiles = new HashSet<FunctionTaskProfile>();
        PersonFunctions = new HashSet<PersonFunction>();
    }

    public int Id { get; set; }
    
    public string Name { get; set; }
    public float? ItemOrder { get; set; }
    

    public virtual Organisation Organisation { get; set; }
    public virtual ICollection<DepartmentFunction> DepartmentFunctions { get; set; }
    public virtual ICollection<FunctionTaskProfile> FunctionTaskProfiles { get; set; }
    public virtual ICollection<PersonFunction> PersonFunctions { get; set; }
    public DateTime? DeletedAt { get; set; }
}

DepartmentFunction 中间表实体类

public class DepartmentFunction 
{
    
    public int FunctionId { set; get; }
    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
    public virtual Function Function { get; set; }
}

将EF Core 5升级到EF Core 7后,无论用预加载还是懒加载加载任一实体的DepartmentFunction集合时,每个唯一的DepartmentFunction条目都会被重复列出两次。

我尝试过显式配置关联关系,但问题依然存在,配置代码如下:

modelBuilder.Entity<DepartmentFunction>(entity =>
    {
        entity.HasKey(e => new {FunctieId = e.FunctionId, AfdelingId = e.DepartmentId})
            .HasName("PK__Afdeling__591131EC594F97A1");

        entity.HasOne(d => d.Department)
            .WithMany(p => p.DepartmentFunctions)
            .HasForeignKey(d => d.DepartmentId)
            .OnDelete(DeleteBehavior.ClientSetNull);

        entity.HasOne(d => d.Function)
            .WithMany(p => p.DepartmentFunctions)
            .HasForeignKey(d => d.FunctionId)
            .OnDelete(DeleteBehavior.ClientSetNull);
                    
    });

我了解到一种需要修改大量现有代码的解决方案,但这样要改动数百处引用,成本太高,希望找到更可行的解决方案。


内容的提问来源于stack exchange,提问作者Daniel Stegeman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:05:42