繁体   English   中英

EntityFramework中的Selft引用表(插入错误)

[英]Selft referencing table in EntityFramework (Insert error)

我有以下实体:

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. 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实现此目的?

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

嗨,我现在不能尝试此代码,但我认为这可以工作:)

是您的桌子的例子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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