首页 > 解决方案 > 实体框架迁移上表关系不正确?

问题描述

演示三种类型关系的简单模型:

一对一 - 契约和房子:房子有 1 契约,1 契约是那个房子的

一对多 - 房子 -> 房间:我的房子有很多房间

多对多 - 房间 <-> 颜色:许多房间可以有许多相同的颜色

类(没有构造函数):

 public class Deed   {
     public int DeedId { get; set; }
     public string Owner { get; set; }
     public House Home { get; set; }

  public class House
  {
    public int HouseId { get; set; }
    public string Address { get; set; }
    public List<Room> Rooms { get; set; }

  public class Room
  {
    public int RoomId { get; set; }
    public string Name { get; set; }
    List<Color> Colors { get; set; }

  public class Color
  {
    public int ColorId { get; set; }
    public string ColorName { get; set; }
    public List<Room> Rooms { get; set; }

我的困惑在于 Migration UP 构造函数:首先是一对一的:当 Deed 和 House 指向对方说它无法确定“原则”时,我得到一个错误。所以我把Deed作为原则:

与家 1 对 1 契约

Next House 有很多房间。我想我知道外键只存在于每个指向房子的房间中,如下所示: 在此处输入图像描述

接下来是我真正感到困惑的地方。我希望许多房间共享许多颜色(多对多)......每个都会指向另一个。但:

在此处输入图像描述

我很感激你的建议。在此先感谢,Yogi(“查克”)

标签: entity-frameworkmany-to-manyentity-framework-migrations

解决方案


尝试对您的模型进行轻微清理。另外,为什么一所房子没有多个契约?无论如何,EF6 使得建模 1-1 关系变得困难。您要么必须将 DeedId 设为 FK,要么将 Deed 设为复杂类型而不是实体。

public class Deed
{
    public int DeedId { get; set; }
    public string Owner { get; set; }
    public int HouseId { get; set; }
    public House House { get; set; }
}

public class House
{
    public int HouseId { get; set; }
    public string Address { get; set; }
    public virtual ICollection<Room> Rooms { get; } = new HashSet<Room>();
}
public class Room
{
    public int RoomId { get; set; }
    public string Name { get; set; }
    public int HouseId { get; set; }
    public House House { get; set; }
    public virtual ICollection<Color> Colors { get; } = new HashSet<Color>();
}
public class Color
{
    public int ColorId { get; set; }
    public string ColorName { get; set; }
    public virtual ICollection<Room> Rooms { get; } = new HashSet<Room>();

}
 public class MyDbContext : DbContext
{
    public DbSet<Deed> Deeds { get; set; }
    public DbSet<House> Houses { get; set; }
    public DbSet<Room> Rooms { get; set; }
    public DbSet<Color> Colors { get; set; }

}

推荐阅读