0

I have the following entity:

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 is able to create the schema just fine but has problems when inserting data with the following code:

var category = new Category();
category.Name = "1";
category.Description = "1";
category.Parent = category;

using (var context = new Context())
{
    context.Categories.Add(category);

    context.SaveChanges();
}

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

I am guessing that this is due to the ParentId field being non-nullable (which is the intention). Without the use of an ORM, I would normally:

  • Set the column type to nullable.
  • Create a master category to auto-generate the primary key.
  • Set the ParentId to the newly generated primary key.
  • Set the column type to non-nullable again.

How could I achieve this with EntityFramework?

Raheel Khan
  • 14,205
  • 13
  • 80
  • 168
  • I dont think you can insert a row into sql table which references to itself and the reference is non nullable and that is the main problem here. – Janne Matikainen May 21 '14 at 11:35

1 Answers1

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

hi, I can't try this code now but I think this will work :)

Here is example with your table.

Mariusz
  • 442
  • 5
  • 16