简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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