2011-03-10 48 views
4

我想知道EF CodeFirst是否會在下面的例子中自動跟蹤「子」對象。添加到父項時是否自動跟蹤子實體?

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

這裏是我(簡化)域實體

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

是的,當你得到你Order從上下文和添加新OrderLineDbContext將其插入到數據庫調用SaveChanges。它還會跟蹤所有更改以加載OrderLines。唯一的例外可以是刪除現有的OrderLine。如果您的OrderLine只有PK OrderLineIdOrder.OrderLines中刪除OrderLine collectin不會刪除數據庫中的OrderLine,而是將它的OrderId設置爲空(=您的情況爲異常)。如果OrderLineIdOrderId都是您的OrderLine實體中的PK,則從Order.OrderLines刪除OrderLine也將在數據庫中刪除OrderLine

+0

@jessegavin:您對答案滿意嗎?還是您需要澄清? – 2011-03-22 22:45:37