2016-06-07 212 views
0

我有这两个类,我想添加一对多的关系。一对多的关系 - 代码优先

一个怪物只有一个位置

位置可以有很多怪物

但是,当我尝试Update-Database

ALTER TABLE语句冲突与外键我得到这个错误约束“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; } 
} 

回答

0

尝试清除Location表中的现有数据......或者让您的FK在您的Monsters表中为空。

0

在你的环境下,你可以使用:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Location>() 
      .HasMany(l => l.Monsters) 
} 
相关问题