【问题标题】:Selft referencing table in EntityFramework (Insert error)实体框架中的自引用表(插入错误)
【发布时间】:2014-05-21 11:10:59
【问题描述】:

我有以下实体:

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

【问题讨论】:

  • 我不认为你可以在引用自身的 sql 表中插入一行,并且引用不可为空,这是这里的主要问题。

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


【解决方案1】:
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 是您的表的示例。

【讨论】:

  • 他特别希望 ParentId 不可为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多