Are child entities automatically tracked when added to a parent?

痞子三分冷 提交于 2019-12-10 15:14:35

问题


I want to know whether EF CodeFirst will automatically track "child" objects in the example below.

var db = MyDataContext();
var order = db.Orders.Find(orderId);
order.AddOrderLine("Fancy Product");
db.Commit();

Here are my (simplified) domain entities

public class OrderLine {
  public Guid OrderLineId { get; private set; }
  public Guid OrderId { get; private set; }
  public string Description { get; private set; }

  public OrderLine(Guid orderId, string description) {
    OrderLineId = Guid.NewGuid();
    OrderId = orderId;
    Description = description;
  }
}

public class Order : Aggregate {
  public Guid OrderId { get; private set; }
  public ICollection<OrderLine> OrderLines { get; private set; }

  public void AddOrderLine(string description) {
    OrderLines.Add(new OrderLine(OrderId, description));
  }
}

回答1:


Yes, when you get your Order from context and add the new OrderLine, DbContext will insert it to database calling SaveChanges. It will also track all changes to loaded OrderLines. The only exception can be deleting existing OrderLine. If your OrderLine has PK only OrderLineId removing OrderLine from Order.OrderLines collectin will not delete OrderLine in database but instead it will set its OrderId to null (= exception in your case). If both OrderLineId and OrderId are PK in your OrderLine entity removing OrderLine from Order.OrderLines will also delete OrderLine in database.



来源:https://stackoverflow.com/questions/5267164/are-child-entities-automatically-tracked-when-added-to-a-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!