Are child objects automatically tracked when a parent is added?

I want to know if EF CodeFirst will automatically track "children" in the example below.

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

Here are my (simplified) domain objects

 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)); } } 
+4
source share
1 answer

Yes, when you get Order from the context and add a new OrderLine , DbContext inserts it into the database calling SaveChanges . It also keeps track of all changes to loaded OrderLines . The only exception may be the removal of an existing OrderLine . If your OrderLine has only PK OrderLineId removing OrderLine from Order.OrderLines , the collection will not remove OrderLine in the database, but instead will set its OrderId to null (= exception in your case). If both OrderLineId and OrderId are PK in your OrderLine entity that removes OrderLine from Order.OrderLines also removes OrderLine in the database.

+4
source

Source: https://habr.com/ru/post/1343252/


All Articles