本文介绍了添加到父母时是否自动跟踪子实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道EF CodeFirst是否会在下面的例子中自动跟踪子对象。

  var db = MyDataContext (); 
var order = db.Orders.Find(orderId);
order.AddOrderLine(花式产品);
db.Commit();

这是我的(简化的)域实体

  public class OrderLine {
public Guid OrderLineId {get;私人集合}
public Guid OrderId {get;私人集合}
public string描述{get;私人集合}

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

public class Order:Aggregate {
public Guid OrderId {get;私人集合}
public ICollection< OrderLine> OrderLines {get;私人集合}

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


解决方案

是当您从上下文获取订单并添加新的 OrderLine DbContext 将它插入数据库调用 SaveChanges 。它还将跟踪所有更改加载的 OrderLines 。唯一的例外是删除现有的 OrderLine 。如果你的 OrderLine 只有PK只有 OrderLineId 删除 OrderLine code> Order.OrderLines collectin不会在数据库中删除 OrderLine ,而是将其 OrderId 到null(=你的情况下的异常)。如果 OrderLineId OrderId 在您的 OrderLine 实体中是PK从 Order.OrderLines 中删除​​ OrderLine 也将删除 OrderLine 数据库。


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.

这篇关于添加到父母时是否自动跟踪子实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 16:36