在Entity Framework Code First中避免循环依赖

时间:2013-01-17 06:59:55

标签: c# entity-framework ef-code-first entity-framework-5

假设我有两个实体: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; }
}

为了将Code-First与Entity Framework一起使用,我必须再添加一个属性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");
    }
}

有没有其他方法可以避免循环依赖并从Employees类中删除属性Nationality

1 个答案:

答案 0 :(得分:4)

使用WithMany()重载来配置映射。

internal class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
        HasKey(f => f.Id);

        HasRequired(e => e.Nationality)
          .WithMany()
          .Map(c => c.MapKey("NationalityId"));

        ToTable("Employees");
    }
}