实体框架中的自引用表(插入错误)

时间:2014-05-21 11:11:00

标签: c# .net entity-framework circular-reference self-reference

我有以下实体:

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实现这一目标?

1 个答案:

答案 0 :(得分:0)

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

嗨,我现在无法尝试此代码,但我认为这样可行:)

Here就是您的表格的示例。