【问题标题】:EF6 One to Many and Many to One between same entitiesEF6 同一实体之间的一对多和多对一
【发布时间】:2014-05-20 15:05:51
【问题描述】:

我正在尝试建立双重关系。假设它是一个团队和球员 - 一个团队有很多球员,但只有一个队长

    public class Team
    {
        public int Id { get; set; }
        public virtual ICollection<Player> Players { get; set; }

        public Player Captain { get; set; }
        public int CaptainId { get; set; }
    }


    public class Player
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [InverseProperty("Players")]
        public virtual Team Team { get; set; }
        public int TeamId { get; set; }
    }

运行更新数据库时,这会导致错误 ALTER TABLE 语句与 FOREIGN KEY 约束“FK_dbo.Teams_dbo.Players_TeamId”冲突。冲突发生在数据库“dev”、表“dbo.Players”、列“Id”中。 (我是从我真实的类名/字段中翻译过来的)

【问题讨论】:

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


    【解决方案1】:

    使用 Fluent API 明确描述您的实体关系。

    modelBuilder.Entity<Team>().HasMany(t => t.Players).WithRequired(p => p.Team).HasForeignKey(p => p.TeamId);
    modelBuilder.Entity<Team>().HasRequired(t => t.Captain).WithMany().HasForeignKey(t => t.CaptainId);
    

    您可以在上面看到 Team->Captain 关系被视为多对一。假设一个给定的球员不能担任多个球队的队长,但是由于 Team->Player 关系是一对多的,所以一个给定的球员无论如何都不会在多个球队中,并且应该很容易确保通过你的用户界面,一个球队的队长也是该球队的球员,因此给定的球员将只能是一个球队的队长。

    【讨论】:

    • 谢谢。知道注释是否可以做到这一点? (我同意这个例子允许奇怪的事情:它是一个非常简化的例子)
    • 对不起,我不使用注释,所以我真的不能说。 Fluent API 让我在描述关系时更具表现力和明确性,所以我坚持这样做。
    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2014-10-27
    • 2013-11-07
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多