[英]Self referencing / parent-child relationship in Entity Framework
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. 在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): 这是我使用的配置(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: 当我尝试保存这样的新类别时,HasMany()和HasOptional()配置都会导致“无法确定相关操作的有效顺序...”异常:
context.Categories.Add(new Category { Name = "test" });
I don't understand why EF doesn't insert the Category with a null parentId. 我不明白为什么EF不插入带有null parentId的Category。 The database allows the ParentId foreign key to be null. 数据库允许ParentId外键为空。
Would you be able to tell me how to do this? 您能告诉我该怎么做吗?
You must define the ParentId
in the category class as nullable to use it as the foreign key property for an optional relationship: 您必须在类别类中将ParentId
定义为可空值,以将其用作可选关系的外键属性:
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. int
属性不能采用null
,因此不能将NULL
表示为数据库列中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.