EF6 One to Many and Many to One between same entit

2019-09-17 18:37发布

问题:

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". The conflict occurred in database "dev", table "dbo.Players", column 'Id'. (I'm translating from my real classnames/fields)

回答1:

Explicitly describe your entity relationship using the 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.