【问题标题】:Avoid circular dependency in Entity Framework Code First在 Entity Framework Code First 中避免循环依赖
【发布时间】:2013-01-17 06:59:55
【问题描述】:

假设我有两个实体: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,我必须再添加一个属性: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

【问题讨论】:

  • 我无法理解 hiding 集合如何解决循环依赖问题。你能解释一下吗?

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


【解决方案1】:

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

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

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

        ToTable("Employees");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2012-02-15
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多