避免在实体框架代码优先的循环依赖
作者:互联网
假设我有两个实体:国籍和雇员,关系为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结合使用,我必须再添加一个属性:不希望进入国籍的员工(它会产生循环依赖):
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");
}
}
还有其他方法可以避免循环依赖并消除不属于国籍类别的员工吗?
解决方法:
使用WithMany()重载来配置映射.
internal class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration()
{
HasKey(f => f.Id);
HasRequired(e => e.Nationality)
.WithMany()
.Map(c => c.MapKey("NationalityId"));
ToTable("Employees");
}
}
标签:ef-code-first,entity-framework-5,c,entity-framework 来源: https://codeday.me/bug/20191031/1975317.html