[英]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.