简体   繁体   English

一对多关系-代码优先

[英]One to many relationship - Code first

I've got these two classes where I want to add a one to many relationship. 我有这两个类,我想在其中添加一对多的关系。

A monster has only one location 一个怪物只有一个位置
But
A location can have many monsters 一个地点可以有很多怪物

But I get this error when I try to Update-Database 但是当我尝试Update-Database时出现此错误

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Monsters_dbo.Locations_LocationId". ALTER TABLE语句与FOREIGN KEY约束“ FK_dbo.Monsters_dbo.Locations_LocationId”冲突。 The conflict occurred in database "Idle", table "dbo.Locations", column 'LocationId'. 在数据库“空闲”的表“ dbo.Locations”的列“ LocationId”中发生了冲突。

Monster 怪物

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; }
}

Location 位置

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; }
}

In your context you could use: 在您的上下文中,您可以使用:

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

尝试清除“位置”表中的现有数据...或使怪兽表中的FK为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM