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
相关产品推荐
相关产品推荐

