开发者

Are child entities automatically tracked when added to a parent?

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));
  }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜