EF6 One to Many and Many to One between same entities

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!