【问题标题】:One to many relationship - Code first一对多关系 - 代码优先
【发布时间】:2016-06-07 11:17:15
【问题描述】:

我有这两个类,我想在其中添加一对多关系。

怪物只有一个位置
但是
一个地方可以有很多怪物

但是当我尝试Update-Database时出现此错误

ALTER TABLE 语句与 FOREIGN KEY 约束“FK_dbo.Monsters_dbo.Locations_LocationId”冲突。冲突发生在数据库“Idle”、表“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; }
}

【问题讨论】:

    标签: c# asp.net-mvc entity-framework model-view-controller


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      在您的上下文中,您可以使用:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-06
        • 1970-01-01
        相关资源
        最近更新 更多