我想創建一個使用實體框架6和SQL Ce數據庫的代碼第一種方法。當我與主客場球隊以及一個賽季創建比賽時,球隊會根據比賽進行更新,但賽季不會。實體框架代碼首次級聯關係
一季由許多團隊和許多遊戲組成。
球隊打很多比賽也出現在許多聯賽的季節。
比賽是聯賽賽季的一部分,擁有主隊和客隊。
public class Season {
public int ID { get; private set; }
public ICollection<Team> Teams;
public ICollection<Game> Games;
}
public class Team {
public int ID { get; private set; }
public string Name {get;set;}
public ICollection<Game> Games;
public ICollection<Season> Seasons;
}
public class Game {
public int ID { get; private set; }
public Season Season;
public Team HomeTeam;
public Team AwayTeam;
}
public class SeasonConfiguration : EntityTypeConfiguration<Season> {
public SeasonConfiguration() {
HasKey(s => s.ID);
HasMany(g => g.Games).WithOptional(s => s.Season);
//I've read that this should work for a many-to-many relationship, but it doesn't seem to work here!
HasMany(t => t.Teams).WithMany(p => p.Seasons).Map(x =>
{
x.MapLeftKey("TeamID");
x.MapRightKey("SeasonID");
x.ToTable("SeasonTeams");
});
}
public class TeamConfiguration : EntityTypeConfiguration<Team> {
public TeamConfiguration() {
HasKey(t => t.ID);
HasMany(g => g.Games).WithOptional(t => t.AwayTeam).Map(m => m.MapKey("AwayTeamID"));
HasMany(g => g.Games).WithOptional(t => t.HomeTeam).Map(m => m.MapKey("HomeTeamID"));
}
public class GameConfiguration : EntityTypeConfiguration<Game> {
public GameConfiguration() {
HasKey(a => a.ID);
HasOptional(s => s.Season).WithMany(g => g.Games).Map(m => m.MapKey("SeasonID"));
HasOptional(t => t.HomeTeam).WithMany().Map(m => m.MapKey("HomeTeamID"));
HasOptional(t => t.AwayTeam).WithMany().Map(m => m.MapKey("AwayTeamID"));
}
}
當應用程序運行並且使用種子值創建數據庫時,它會創建一個帶有SeasonID和TeamID的SeasonTeams表。
當一個包括球隊和賽季在內的球隊加入比賽時,賽季球隊表不會更新,因此,當我嘗試從一個賽季中獲得所有球隊時,什麼都不會返回。即。
下面的代碼通常是我如何使用上述,但是,沒有給出結果。如預期
Season season2016 = new Season("2016");
Game game = new Game {HomeTeam= "Leicester City", AwayTeam="Arsenal", Season=season2016};
context.SaveChanges();
Season season = GetSeason();
foreach(Team team in season.Teams) {
Console.WriteLine(team.Name);
}
Season.Games的其他查詢,Team.Games & Team.Season工作。
我是第一次使用實體框架進行代碼開發的新手,因此現在摸索了很多,上面的一些代碼可能不是最優的。歡迎任何有關改進的建議,以及對我的問題的幫助。
理想情況下,我希望季節更新,當我添加一個參考賽季的遊戲,但不知道如何實現這一點,請協助。
預先感謝您。
我剛纔d EF不支持多對多關係。我懷疑這就是爲什麼我的代碼不起作用。 – Craig
我有種解決了這個問題,在Game.Season Set屬性中添加了一個檢查,並且在Game.HomeTeam&Game.AwayTeam Set屬性中檢查了Season.Teams集合中是否存在團隊並添加它,如果它沒有「T。我不相信這是一個非常優雅的解決方案。 – Craig
多對多的關係是可能的EF代碼第一=> modelBuilder.Entity() .HasMany (S => s.Contacts) .WithMany(C => c.Customers) .MAP (cs => {c .MapLeftKey(「CustomerId」); cs。MapRightKey( 「使用ContactID」); cs.ToTable(「CustomersContacts」); }); –
Alegrowin