EF6一对多和一对一相同实体之间 [英] EF6 One to Many and Many to One between same entities
问题描述
public class Team
{
public int Id {get;组; }
public virtual ICollection< Player>玩家{get;组; }
public Player Captain {get;组; }
public int CaptainId {get;组; }
}
public class Player
{
public int Id {get;组; }
public string Name {get;组; }
[InverseProperty(Players)]
public virtual Team Team {get;组; }
public int TeamId {get;组; }
}
当运行update-database时,会导致沿着
ALTER TABLE语句与FOREIGN KEY约束FK_dbo.Teams_dbo.Players_TeamId冲突。冲突发生在数据库dev,表dbo.Players,列Id。 (我正在从我真正的类名/字段翻译)
使用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的关系是一对多的,所以一个给定的球员不在一个队伍上,而且应该很容易确保你的用户界面,一个团队的队长也是该队的一名球员,因此一名给定的球员只能是一队的队长。
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.
这篇关于EF6一对多和一对一相同实体之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!