c# - 避免 Entity Framework Code First 中的循环依赖

标签 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; }
}

为了在 Entity Framework 中使用 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; }
}

这样我就可以在配置类中配置关系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");
    }
}

关于c# - 避免 Entity Framework Code First 中的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14373720/

相关文章:

c# - 两个不同数据库的 Entity Framework 代码优先迁移

entity-framework - 循环遍历 DBContext 上的所有 DBSet(属于 TEntity)

c# - DBcontext.Database.Log : executable sql query

c# - MVC - Entity Framework - 这属于哪里?

c# - EF 4.1 代码优先 : Many to Many

c# - 了解 LINQ to SQL 中的 .AsEnumerable()

C# lambda 表达式作为函数参数

c# - 什么线程在 silverlight WCF 调用中调用完成的事件处理程序?

c# - 如何在 url 中包含 Jquery UI 选项卡的 id?

c# - Entity Framework 和linq之间的混淆