添加到父实体时是否会自动跟踪子实体?
我想知道 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));
}
}
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));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,当您从上下文获取
Order
并添加新的OrderLine
时,DbContext
会调用SaveChanges
将其插入到数据库中>。它还将跟踪加载的OrderLines
的所有更改。唯一的例外是删除现有的OrderLine
。如果您的OrderLine
仅具有 PKOrderLineId
,则从Order.OrderLines
中删除OrderLine
时,collectin 不会删除OrderLine< /code> 在数据库中,但它会将其
OrderId
设置为 null (= 在您的情况下是例外)。如果OrderLineId
和OrderId
在您的OrderLine
实体中都是 PK,则从Order.OrderLinesOrderLine
code> 还将删除数据库中的OrderLine
。Yes, when you get your
Order
from context and add the newOrderLine
,DbContext
will insert it to database callingSaveChanges
. It will also track all changes to loadedOrderLines
. The only exception can be deleting existingOrderLine
. If yourOrderLine
has PK onlyOrderLineId
removingOrderLine
fromOrder.OrderLines
collectin will not deleteOrderLine
in database but instead it will set itsOrderId
to null (= exception in your case). If bothOrderLineId
andOrderId
are PK in yourOrderLine
entity removingOrderLine
fromOrder.OrderLines
will also deleteOrderLine
in database.