简体   繁体   English

实体框架:将子记录添加到现有父记录中

[英]Entity Framework: Add child record to and existing parent

I need to add a child record to and existing parent. 我需要将子记录添加到现有父记录中。

I call the following methods 我称以下方法

_handler.Update(custOrder);
_handler.Save();


public TEntity Update(TEntity entity)
        {
            Entities.Attach(entity);
            DataContext.Entry(entity).State = EntityState.Modified;
            return entity;
        }

and

  public void Save() {
            try
            {
                base.SaveChanges();
            }
            catch (Exception e) { }
        }

The custOrder contains the parent (which already exists) and a new child record that needs to be added. 该custOrder包含一个父级(已经存在)和一个需要添加的新子级记录。 Eg Adding an order item for an existing order. 例如,为现有订单添加订单商品。

However when I execute this the child does not get added. 但是,当我执行此操作时,不会添加该子级。

I am not sure how specify that the parent has not changed but a child was added 我不确定如何指定父级没有更改但是添加了一个子级

Please advice. 请指教。

I finally got the answer it was a bit subtle have to admit, The parent entity needed to be added instead of attached and the state set to modified afterwards. 我终于得到一个必须承认的微妙答案,需要添加父实体而不是附加实体,然后将状态设置为修改。

 public TEntity Update(TEntity entity)
        {
            Entities.Add(entity);
            DataContext.Entry(entity).State = EntityState.Modified;
            return entity;
        }

You need to tell EF that the child itself was actually added. 您需要告诉EF该孩子本身已被添加。 It won't assume from the parent that something needs to be added when the EntityState is set to Modified. 当EntityState设置为Modified时,它不会从父级假设需要添加某些内容。 You need to Add that new child record to the context, and then run the save. 您需要将该新的子记录添加到上下文中,然后运行保存。

Assuming OrderItem class as your child: 假设OrderItem类为您的孩子:

dbContext.OrderItems.Add(myNewOrderItem);
dbContext.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架在知道父项的情况下插入子项记录 - Entity Framework Inserting child record with parent knowing 新子项在Entity Framework 4中插入现有父项 - New child inserts existing parent in Entity Framework 4 使用 Entity Framework 6 将父实体与数据库中现有的子实体连接起来 - Connect parent entity with existing child entity in database using Entity Framework 6 与子记录一起更新父记录 - 实体框架核心 - Update parent record along with child record - entity framework core 实体框架-将子对象添加到父对象 - Entity Framework - Add child object to parent 实体框架4 - 查询父表和急切加载1(单个)子记录 - Entity Framework 4 - Query parent table and eager load 1 (single) child record 在Entity Framework中添加子记录时,如何避免创建父记录? - How to avoid creating a parent when adding a child record in Entity Framework? 实体框架:使用新的父对象更新现有的子对象 - Entity Framework : Updating an existing child object with a new parent object 实体框架通过多对多关系将现有子级添加到新父级 - Entity Framework adding existing Child to a new Parent on a many to many relation 实体框架通过多对多关系将现有子级分配给父级 - Entity Framework assign existing child to parent on a many-to-many relation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM