在试图弄清楚如何使用 Code First 在实体框架中实现双向 1..n 关系时,我感到非常困惑。例如,一个团队(由一个 Team 实体表示)有一个教练和一个经理(都由一个 Person 实体表示)。所以,我的团队模型可能如下:
public class Team
{
public Team()
{
Manager = new Person();
Coach = new Person();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TeamID { get; set; }
public string Name { get; set; }
[ForeignKey("Manager")]
public int ManagerID { get; set; }
public virtual Person Manager { get; set; }
[ForeignKey("Coach")]
public int CoachID { get; set; }
public virtual Person Coach { get; set; }
}
我可以通过实现 Person Entity 来实现单向导航,如下所示:
public class Person
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonID { get; set; }
public string Name { get; set; }
}
和流畅的 API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Team>()
.HasRequired(t => t.Manager);
modelBuilder.Entity<Team>()
.HasRequired(t => t.Coach);
base.OnModelCreating(modelBuilder);
}
但是,虽然这允许我从 Team 实体导航到相关的 Coach 和 Manager(两个 Person 实例),但它不允许我直接从 Coach 或 Manager 导航到相关的 Team。所以,为了实现双向导航,我修改了 Person 实体如下:
public class Person
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonID { get; set; }
public string Name { get; set; }
[ForeignKey("Team")]
public int TeamID { get; set; }
public virtual Team Team { get; set; }
}
虽然构建正常,但当我尝试保存到数据库时出现以下运行时错误:
System.Data.Entity.Core.UpdateException
InnerException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
因此,为了指定实体之间的顺序,我尝试通过添加“WithRequiredPricipal”来修改流畅的 API,如下所示:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Team>()
.HasRequired(t => t.Manager)
.WithRequiredPrincipal(t => t.Team);
modelBuilder.Entity<Team>()
.HasRequired(t => t.Coach)
.WithRequiredPrincipal(t => t.Team);
base.OnModelCreating(modelBuilder);
}
但是,当我尝试在包管理器控制台中执行“添加迁移”时,我收到以下错误:
System.InvalidOperationException: The navigation property 'Team' declared on type 'RelatedEntities.Models.Person' has been configured with conflicting foreign keys.
我试图实现的目标似乎是一个简单的要求,但我已经做了很多寻找解决方案的工作,但还没有找到答案。我在流畅的 API 或注释中遗漏了什么吗?
(我不想实现解决方法,例如为教练和经理实现单独的模型,因为一个团队可能有许多其他角色(例如,助理教练、公共关系经理等)。我希望每个角色都只是一个实例个人实体。)