C# 首先使用实体框架代码从同一父表中获得两个外键,而不必指定父实体上的集合
所以我在尝试获取两个外键来访问一个表时遵循了这一点,并且它可以工作C# 首先使用实体框架代码从同一父表中获得两个外键,而不必指定父实体上的集合,c#,entity-framework,orm,ef-code-first,C#,Entity Framework,Orm,Ef Code First,所以我在尝试获取两个外键来访问一个表时遵循了这一点,并且它可以工作 public class Team { public int TeamId { get; set;} public string Name { get; set; } public virtual ICollection<Match> HomeMatches { get; set; } public virtual ICollection<Match> AwayMatches
public class Team
{
public int TeamId { get; set;}
public string Name { get; set; }
public virtual ICollection<Match> HomeMatches { get; set; }
public virtual ICollection<Match> AwayMatches { get; set; }
}
public class Match
{
public int MatchId { get; set; }
public int HomeTeamId { get; set; }
public int GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
public class Context : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Match>()
.HasRequired(m => m.HomeTeam)
.WithMany(t => t.HomeMatches)
.HasForeignKey(m => m.HomeTeamId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Match>()
.HasRequired(m => m.GuestTeam)
.WithMany(t => t.AwayMatches)
.HasForeignKey(m => m.GuestTeamId)
.WillCascadeOnDelete(false);
}
}
如何使用modelBuilder向EntityFramework表达我希望HomeTeamID和GuestetteAmid成为团队外键的内容?只需删除集合并为
保留空参数。WithMany()
所以您只需要简单的导航属性?然后只需删除集合并为.WithMany()
保留空参数。另外,您可以使用属性ForeignKey[“ID\u field\u name”]
@Lanorkin-嗨,谢谢,我没想到您可以不带任何东西通过WithMany()。你应该加上这个作为答案。当有两个字段都指向同一个表时,我发现ForeignKey属性变得混乱。
public class Team
{
public int TeamId { get; set;}
public string Name { get; set; }
// HomeMatches and AwayMatches collection is no longer here
}