C# 父记录不是';t在添加子记录后添加到数据库

C# 父记录不是';t在添加子记录后添加到数据库,c#,database,entity-framework,ef-code-first,relational-database,C#,Database,Entity Framework,Ef Code First,Relational Database,我试图使用代码优先的方法创建一个包含单个自引用表“Categories”的数据库。以下是POCO实体类别的定义: public class Category { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int CategoryId { get; private set; } public string Name { get; set; } public int?

我试图使用代码优先的方法创建一个包含单个自引用表“Categories”的数据库。以下是POCO实体类别的定义:

public class Category
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryId { get; private set; }
    public string Name { get; set; }
    public int? ParentCategoryId { get; private set; }

    [ForeignKey("ParentCategoryId")]
    public Category ParentCategory { get; set; }
    public List<Category> SubCategories { get; set; }
    public Category()
    {
        SubCategories = new List<Category>();
    }
}
但我在结果表中看到的唯一记录是“child”记录。但是如果我将
parent.SubCategories.Add(child)
行更改为
child.ParentCategory=parent
行,一切都会正常工作,并且表将包含这两条记录。如果我将
context.Categories.Add(child)
更改为
context.Categories.Add(parent)
,一切都会好起来的

那么,我做错了什么?为什么不将父记录与其子记录一起添加到表中?如何在不进行上述替换的情况下实现所需的行为


任何帮助都将不胜感激。

您之所以会有这种行为,是因为您这么说只是为了添加chield

context.Categories.Add(child);
若你们看你们的子对象,它和你们的父对象并没有关联,但你们的父对象和子对象有关联(单向关系),所以当你们做context.Categories.Add(child);EF没有关于父项的线索

所以正确的方法是只添加父对象

context.Categories.Add(parent);
更改后的代码应类似于

using (var context = new CategoryContext())
{
    var child = new Category { Name = "child" };
    var parent = new Category { Name = "parent" };
    parent.SubCategories.Add(child);
    context.Categories.Add(parent);
    context.SaveChanges();
}


如果这有帮助的话,请不要忘记将其标记为答案:)

哦,现在我明白了。Category是一个普通的CLR(不是EF)类,因此EF无法跟踪某个实例是否已添加到另一个实例的子集合中。很明显:(
context.Categories.Add(parent);
using (var context = new CategoryContext())
{
    var child = new Category { Name = "child" };
    var parent = new Category { Name = "parent" };
    parent.SubCategories.Add(child);
    context.Categories.Add(parent);
    context.SaveChanges();