简体   繁体   中英

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

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Monsters_dbo.Locations_LocationId". The conflict occurred in database "Idle", table "dbo.Locations", column '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为空。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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