简体   繁体   English

EF6同一实体之间一对多和多对一

[英]EF6 One to Many and Many to One between same entities

I'm trying to create a double relationship. 我正在尝试建立双重关系。 Lets say its a Team and Players - a Team has many Players but only one captain 可以说这是一个团队和一个球员-一个团队有很多球员,但只有一名队长

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

When running update-database this is resulting in an error along the lines of The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Teams_dbo.Players_TeamId". 运行更新数据库时,这会导致ALTER TABLE语句的行与FOREIGN KEY约束“ FK_dbo.Teams_dbo.Players_TeamId”冲突。 The conflict occurred in database "dev", table "dbo.Players", column 'Id'. 数据库“ dev”的表“ dbo.Players”的列“ Id”中发生了冲突。 (I'm translating from my real classnames/fields) (我是从我真实的班级名/领域翻译过来的)

Explicitly describe your entity relationship using the Fluent API. 使用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);

You can see above that the Team->Captain relationship is treated as a many-to-one. 您可以在上方看到“团队”-“队长”关系被视为多对一关系。 Presumably a given player can't be captain of more than one team, but since the Team->Player relationship is one-to-many, a given player isn't on more than one team anyway and it should be easy to ensure through your UI that a team's captain is also a player for that team and thus a given player will only be captain for one team. 假定一个给定的球员不能担任一个以上球队的队长,但是由于Team-> Player关系是一对多的,因此给定的球员无论如何都不会在一个以上的球队中,因此应该很容易确保您的用户界面,即某队的队长也是该队的球员,因此给定的球员将仅是一个队的队长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM