我有2代表在我的數據庫:實體框架組合鍵映射
遊戲:
public class Game
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[ForeignKey("WinningSlot"), Column(Order = 0)]
public int Id { get; set; }
public int numer { get; set; }
public string md5 { get; set; }
public string secret { get; set; }
public GameStatus Status { get; set; }
public int SlotsNumber { get; set; }
public DateTime CreationTime { get; set; }
public DateTime? EndDime { get; set; }
public DateTime? ForceEndTime { get; set; }
[ForeignKey("WinningSlot"), Column(Order = 1)]
public int WinningSlotId { get; set;
public GameSlot WinningSlot { get; set; }
public double SlotPrice { get; set; }
public List<GameSlot> Slots { get; set; }
}
GameSlot:
public class GameSlot
{
[Column(Order = 0), Key]
public int GameId { get; set; }
[ForeignKey("GameId")]
public Game Game { get; set; }
[Column(Order = 1), Key]
public int Slot { get; set; }
public int? PlayerId { get; set; }
[ForeignKey("PlayerId")]
public WotUser Player { get; set; }
public string SecretData { get; set; }
}
,你可以看到GameSlot
表的PK是複合並由GameID
(也是FK到Game
)和Slot
(它是插槽編號)組成。一切正常,直到我試圖將WinningSlot
屬性添加到我的Game
表中。它會在數據庫更新的GameSlot
表中爲它生成另一個Game_Id
列。
我所有試圖搞糊塗api的嘗試都失敗了。你能幫助我,請建立一個正常的關係,這個工作? winningslot
列是可選的,可以爲空。謝謝!
更新: 問題與FluentApi解決:
modelBuilder.Entity<Game>()
.HasOptional(g => g.WinningSlot)
.WithMany()
.HasForeignKey(g => new { g.Id, g.WinningSlotId });
但這裏是另一個: 當我嘗試添加插槽像這樣(示例代碼),它工作正常:
var game = db.Games.Find(1);
game.WinningSlotId = 1;
db.SaveChanges();
但如果我想設置插槽,請改爲:
var game = db.Games.Find(1);
var gameslot = db.Slots.Find(game.Id, 1);
game.WinningSlot = gameslot;
db.SaveChanges();
它會拋出一個異常告訴我,我不能修改遊戲的Id屬性。這裏有什麼錯誤,如果gameslot有它的gameID = game.Id?