在EntityFramework中自引用表(插入错误)

本文关键字:插入 错误 EntityFramework 自引用 | 更新日期: 2023-09-27 18:04:19

我有以下实体:

public class Category
{
    public virtual long Id { get; set; }
    public string Name { get; set; }
    public virtual long ParentId { get; set; }
    public virtual Category Parent { get; set; }
    public virtual List<Category> Categories { get; set; }
}
public class CategoryConfiguration:
    EntityTypeConfiguration<Category>
{
    public CategoryConfiguration ()
    {
        this.HasKey(entity => entity.Id);
        this.Property(entity => entity.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        this.HasRequired(entity => entity.Parent).WithMany(entity => entity.Categories).HasForeignKey(entity => entity.ParentId);
        this.HasMany(entity => entity.Categories).WithRequired(entity => entity.Parent).HasForeignKey(entity => entity.ParentId);
        this.Property(entity => entity.Name).IsRequired().HasMaxLength(1000);
    }
}

EF能够很好地创建模式,但是在使用以下代码插入数据时出现问题:

var category = new Category();
category.Name = "1";
category.Description = "1";
category.Parent = category;
using (var context = new Context())
{
    context.Categories.Add(category);
    context.SaveChanges();
}

错误:Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

我猜这是由于ParentId字段是non-nullable(这是意图)。如果不使用ORM,我通常会:

  • 设置列类型为nullable
  • 创建一个主类别,自动生成主键
  • 设置ParentId为新生成的主键
  • 再次设置列类型为non-nullable

我怎么能实现这与EntityFramework?

在EntityFramework中自引用表(插入错误)

public class Category
{
    public long Id { get; set; }
    public string Name { get; set; }

  public long? ParentID { get; set; }
  public Category Parent { get; set; }
}

modelBuilder.Entity<Category>().
      HasOptional(c => c.Parent).
      WithMany().
      HasForeignKey(m => m.ManagerID);

嗨,我现在不能尝试这个代码,但我认为这将工作:)