我有多個字段是外鍵到另一個表的主鍵的表。例如:多個外鍵同主鍵表
Fixture Id (PK)
HomeTeamId (FK to Team.TeamId)
AwayTeamId (FK to Team.TeamId)
HomeTeamCoachId (FK to Coach.CoachId)
AwayTeamCoachId (FK to Coach.CoachId)
它會更好這個數據與外鍵FixtureId分成2個表HomeTeam和AwayTeam?這是目前由實體框架生成的內容:
public partial class Fixture
{
public int FixtureId { get; set; }
//foreign key
public int AwayTeamId { get; set; }
//navigation properties
public virtual Team AwayTeam { get; set; }
//foreign key
public int HomeTeamId { get; set; }
//navigation properties
public virtual Team HomeTeam { get; set; }
//foreign key
public int AwayCoachId { get; set; }
//navigation properties
public virtual Coach AwayCoach { get; set; }
//foreign key
public int HomeCoachId { get; set; }
//navigation properties
public virtual Coach HomeCoach { get; set; }
}
可有人告訴我,如果這是這樣做的正確方法:
FixtureId PK
HomeTeamId int
AwayTeamId int
HomeTeamCoachId int
AwayTeamCoachId int
AwayTeam_TeamId FK
HomeTeam_TeamId FK
AwayTeamCoach_CoachId FK
HomeTeamCoach_CoachId FK
這是通過這個類產生的?
編輯:在回答Slauma
所以我的課基本上會是這樣?或者在OnModelCreating中的配置是否意味着我不需要一些與我的Fixture類相關的外鍵代碼?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Entity Type Configuration
modelBuilder.Configurations.Add(new TeamConfiguration());
modelBuilder.Configurations.Add(new CoachConfiguration());
modelBuilder.Configurations.Add(new FixtureConfiguration());
modelBuilder.Entity<Fixture>()
.HasRequired(f => f.AwayTeam)
.WithMany()
.HasForeignKey(f => f.AwayTeamId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Fixture>()
.HasRequired(f => f.HomeTeam)
.WithMany()
.HasForeignKey(f => f.HomeTeamId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Fixture>()
.HasRequired(f => f.AwayCoach)
.WithMany()
.HasForeignKey(f => f.AwayCoachId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Fixture>()
.HasRequired(f => f.HomeCoach)
.WithMany()
.HasForeignKey(f => f.HomeCoachId)
.WillCascadeOnDelete(false);
}
public partial class Fixture
{
public int FixtureId { get; set; }
public string Season { get; set; }
public byte Week { get; set; }
//foreign key
public int AwayTeamId { get; set; }
//navigation properties
public virtual Team AwayTeam { get; set; }
//foreign key
public int HomeTeamId { get; set; }
//navigation properties
public virtual Team HomeTeam { get; set; }
//foreign key
public int AwayCoachId { get; set; }
//navigation properties
public virtual Coach AwayCoach { get; set; }
//foreign key
public int HomeCoachId { get; set; }
//navigation properties
public virtual Coach HomeCoach { get; set; }
public byte AwayTeamScore { get; set; }
public byte HomeTeamScore { get; set; }
}
我看不出什麼毛病有含多處e FK引用同一張表(例如'團隊') - 那完全沒問題。 –
從技術上講沒問題。邏輯上也許。我認爲球隊和教練是相關的,所以主隊不能只有主教練。你可能想要模擬一個TeamCoach表(FK的團隊和教練),並在'Fixture'中有'TeamCoach'的引用,而不是'Team'和'Coach'。 –
球隊和教練是相關的,但一個球隊的教練可以改變,所以使用TeamId獲得教練並不總是成功,因爲這張球隊將持有歷史數據,而球隊可能會經歷幾個不同的教練。 – user517406