c# - Entity Framework 5 Code First 自引用关系

标签 c# entity-framework foreign-keys entity-framework-5

如何在 Entity Framework 5 中映射以下关系?

public class Item {
  public int Id { get; set; }
  public int? ParentItemId { get; set; }
  public string Value { get; set; }

  public Item ParentItem { get; set; }
  public List<Item> ChildItems { get; set; }
}

我已经试过了:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
  base.OnModelCreating(modelBuilder);

  modelBuilder.Entity<Item>()
              .HasOptional(i => i.ParentItem)
              .WithMany(i => i.ChildItems)
              .HasForeignKey(i => i.ParentItemId);
}

还有这个:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
  base.OnModelCreating(modelBuilder);

  modelBuilder.Entity<Item>()
              .HasMany(i => i.ChildItems)
              .WithOptional(i => i.ParentItem)
              .HasForeignKey(i => i.ParentItemId);
}

两者都会导致此错误:

引用约束的 Dependent Role 中的所有属性类型必须与 Principal Role 中相应的属性类型相同。

如果我从数据库优先映射开始,生成的实体如下所示:

public partial class Item
{
    public Item()
    {
        this.ChildItems = new HashSet<Item>();
    }

    public int Id { get; set; }
    public Nullable<int> ParentItemId { get; set; }
    public string Value { get; set; }

    public virtual ICollection<Item> ChildItems { get; set; }
    public virtual Item ParentItem { get; set; }
}

我知道如果我从 db-first 开始这会起作用,我只需要知道如何在代码优先中定义关系。

最佳答案

在代码中首先像这样更改您的实体类:

   public class Item 
   {
      public Item()
      {
            this.ChildItems = new HashSet<Item>();
      }

      public int Id { get; set; }
      public Nullable<int> ParentItemId { get; set; }
      public string Value { get; set; }

      public virtual Item ParentItem { get; set; }
      public virtual ICollection<Item> ChildItems { get; set; }
  }

将以下代码写入您的上下文文件:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Item>()
                    .HasOptional(i => i.ParentItem)
                    .WithMany(i => i.ChildItems)
                    .HasForeignKey(i => i.ParentItemId);
    }

认为这应该可行。

关于c# - Entity Framework 5 Code First 自引用关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18941455/

相关文章:

mysql - 使用数据库关系限制输入

c# - 动态数据显示 : Change X-Axis date time format for graph

C# 7 .NET/CLR/Visual Studio 版本要求

c# - 以编程方式在加载的松散 xaml 文件中的控件上设置文本

c# - Entity Framework 、现有数据库、代码优先 - 忽略数据库列和更改数据类型

django-admin - 为什么 django admin 不接受 Nullable 外键?

c# - 将字节 * 传递给 Stream.Read(byte[], int, int)

mysql - EntityFramework 包含并可能加入?

c# - ASP.NET MVC3 和 Entity Framework - 一个 View 中的一对多关系

postgresql - Postgres : Are Nested Foreign Keys allowed?