首先在实体框架代码中避免循环依赖

本文关键字:循环 依赖 代码 实体 框架 | 更新日期: 2023-09-27 17:53:44

假设我有两个实体:NationalityEmployee,关系为1:n。

public class Employee
{
    public int Id { get; set; }
    // More Properties
    public virtual Nationality Nationality { get; set; }
}
public class Nationality
{
    public int Id { get; set; }
    public string Name { get; set; }
}

为了使用实体框架代码优先,我必须添加一个属性:Employees,我不希望进入Nationality(它创建循环依赖):

public class Nationality
{
    public int Id { get; set; }
    public string Name { get; set; }
    // How to avoid this property
    public virtual List<Employee> Employees { get; set; }
}

这样我就可以在Configuration类中配置关系1:n:

internal class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
        HasKey(f => f.Id);
        HasRequired(e => e.Nationality)
          .WithMany(e => e.Employees)
          .Map(c => c.MapKey("NationalityId"));
        ToTable("Employees");
    }
}

是否有其他方法可以避免循环依赖并消除Nationality类中的Employees属性?

首先在实体框架代码中避免循环依赖

使用WithMany()过载配置映射

internal class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
        HasKey(f => f.Id);
        HasRequired(e => e.Nationality)
          .WithMany()
          .Map(c => c.MapKey("NationalityId"));
        ToTable("Employees");
    }
}