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?