[英]One to many relationship - Code first
我有這兩個類,我想在其中添加一對多的關系。
一個怪物只有一個位置
但
一個地點可以有很多怪物
但是當我嘗試Update-Database
時出現此錯誤
ALTER TABLE語句與FOREIGN KEY約束“ FK_dbo.Monsters_dbo.Locations_LocationId”沖突。 在數據庫“空閑”的表“ dbo.Locations”的列“ LocationId”中發生了沖突。
怪物
public class Monster
{
public Monster()
{
}
public int MonsterId { get; set; }
public string Name { get; set; }
public int Gold { get; set; }
public int Experience { get; set; }
public int Level { get; set; }
public int LocationId { get; set; }
[ForeignKey("LocationId")]
public virtual Location Location { get; set; }
}
位置
public class Location
{
public Location()
{
Monsters = new List<Monster>();
}
public int LocationId { get; set; }
public string Name { get; set; }
public virtual ICollection<Monster> Monsters { get; set; }
}
在您的上下文中,您可以使用:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Location>()
.HasMany(l => l.Monsters)
}
嘗試清除“位置”表中的現有數據...或使怪獸表中的FK為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.