【问题标题】:EF Code First Parent-Child insertions with identity columns带有标识列的 EF Code First 父子插入
【发布时间】:2011-08-03 15:23:22
【问题描述】:

我有以下型号。

class Parent
{
    int ParentId (identity column) { get; set; }
    string ParentName { get; set; }
    virtual ICollection<Child> Children { get; set; }
}

class Child
{
    int ChildId (identity column) { get; set; }
    string ChildName { get; set; }
    int ParentID { get ; set; } //foreign key to Parent(ParentID)
}

如何在单个事务中向我的父母和孩子插入几行?基本上我想获得在父级上生成的标识(比如我在父级中插入一行)并插入具有该值的子行? 如何使用 Code First 实现这一点?

【问题讨论】:

    标签: entity-framework code-first ef-code-first


    【解决方案1】:

    您不必担心 Parent 的 Id 将获得什么值来插入 Child 行。这应该足够了:

    var parent = new Parent
    {
        // fill other properties
    
        Children = new List<Child>()
    }
    
    parent.Children.add(new Child { /*fill values */);
    
    dbContext.Parents.Add(parent); // whatever your context is named
    dbContext.SaveChanges();
    

    作为记录,ID 将在调用 SaveChanges() 后分配,因此如果您真的在插入 Child 实体之前需要 ID,您可以随时调用 SaveChanges() 两次。 p>

    同样,这不应该是必要的。

    顺便说一句,我建议将外键属性从 ChildParent 设为导航属性,因此 Child 类看起来像:

    class Child
    {
        public int ChildId { get; set; } // identity column
        public string ChildName { get; set; }
        public virtual Parent Parent { get ; set; } //foreign key to Parent
    }
    

    这样,您始终可以直接访问 Child 的父级,而无需自己从数据库中显式检索它(它将被延迟加载)。

    【讨论】:

    • 你不是说SaveChangesdbContext.Parents.Add(parent)吗?
    • @Ladislav - 是的,是的,我已经更正了我的答案,谢谢。当我回答这个问题时,我正在查看我自己的工作单元实施,我分心/困惑:)
    • 实体框架先插入Parent,再插入children。 insert into parent --&gt; newly_created_parent_id,然后是 insert into child (..., parent_id) values (..._ newly_created_parent_id)。我对此进行了测试,并且就像您说的那样有效,但是我正在寻找说明此行为的文档。或者这是否太合乎逻辑而无法将其放入文档 (msdn) 中?
    • 由于某种原因它不能自动为我工作,我不得不调用 SaveChanges() 两次。(即添加父项,保存,在子项中设置 ParentId,添加子项,保存)
    【解决方案2】:

    有关如何执行此操作的示例,请参阅新的 EF Code First MVC 教程系列。该系列的第 6 篇就是一个例子。 10 系列中的第一个在这里: http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多