Self referencing / parent-child relationship in Entity Framework

给你一囗甜甜゛ 提交于 2019-11-27 11:44:25

问题


I read quite a number of posts of programmers that run into the Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values -exception when using a self-referencing relationship in Entity Framework.

I am trying to get a parent-child relationship to work:

public class Category {
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public Category Parent { get; set; }
    public List<Category> Children { get; set; }
}

This is the configuration I use (Fluent API):

Property(c => c.ParentId).IsOptional();
HasMany(c => c.Children).WithOptional(c => c.Parent).HasForeignKey(c => c.ParentId);
//HasOptional(c => c.Parent).WithMany(c => c.Children).HasForeignKey(c => c.ParentId);

Both the HasMany() and HasOptional() configurations result in a "Unable to determine a valid ordering for dependent operations..." exception when I try to save a new category like this:

context.Categories.Add(new Category { Name = "test" });

I don't understand why EF doesn't insert the Category with a null parentId. The database allows the ParentId foreign key to be null.

Would you be able to tell me how to do this?


回答1:


You must define the ParentId in the category class as nullable to use it as the foreign key property for an optional relationship:

public int? ParentId { get; set; }

An int property cannot take the value null and therefore cannot represent a NULL as value in a database column.



来源:https://stackoverflow.com/questions/9955491/self-referencing-parent-child-relationship-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!