【问题标题】:A parent record isn't added to a database after a child record has been added添加子记录后,不会将父记录添加到数据库中
【发布时间】:2014-06-09 01:14:35
【问题描述】:

我正在尝试使用 Code First 方法创建一个包含单个自引用表“Categories”的数据库。下面是 Category 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>();
    }
}

这里是数据库的 DbContext 子类的定义:

public class CategoryContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public CategoryContext()
        : base("name=CategoriesEntities") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Category>().HasMany(cat => cat.SubCategories).WithOptional(cat => cat.ParentCategory).HasForeignKey(cat => cat.ParentCategoryId);
    }
}

现在我正在尝试填满表格:

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

但我在结果表中看到的唯一记录是“子”记录。但是如果我将parent.SubCategories.Add(child) 行更改为child.ParentCategory = parent 行,一切都会正常工作,并且表将包含两条记录。如果我将context.Categories.Add(child) 更改为context.Categories.Add(parent),一切都会好起来的。

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

任何帮助将不胜感激。

【问题讨论】:

    标签: c# database entity-framework ef-code-first relational-database


    【解决方案1】:

    你得到这个行为是因为你说它只是为了添加孩子

    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 无法跟踪某个实例是否已添加到另一个实例的子集合中。这很明显:(
    猜你喜欢
    • 2014-07-14
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多