添加 children 时创建 parent object 的新实例

New instance of parent object created when adding children

我创建了一个将 child 属性复制到 parent 属性的函数。让我的 parent class 成为 A 和 class B 的许多 Children。我正在将 children 添加到 A,这已经是其他 parent 的 children(复制 child class 的实例以避免额外的输入值的开销)。我创建了一个 CopyProperty 函数,它将 Parent ID 和所选 ChildInstances 列表作为参数。

Post方法

 public ActionResult CopyProperty(TechnicalCharacteristic model, int[] setid)
 {
    var req_tcset = new List<TcSet>();
    foreach(var item in setid)
        req_tcset.Add(db.TcSet.FirstOrDefault(x => x.TcSetID == item));
    foreach(var item in req_tcset)
    {
        if (!model.TcSets.Any(x => x.TcSetID == item.TcSetID))
        {
           var add = new TcSet { TechnicalCharacteristic = model, TechnicalCharacteristicID = model.TechnicalCharacteristicID };
           add.SetName = item.SetName;
           add.DescriptionDE = item.SetName;
           db.TcSet.Add(add);
           db.SaveChanges();
        }
   }

当我保存 child class 时,同样的 parent class object 也会使用传递模型的相同值创建。我希望将 children 添加到 parent class 而不是 parent class.

的新实例

来自数据库的附加信息

在数据库中,parent 的 ID 也更改为新的模型 ID。我真的不明白为什么会这样。调用 CopyProperty 的 parent class 的 children 被删除并分配给新的 parent,它的所有细节都与原来parent。但最后我有多个 parent 的副本。

因为您是在这一行的代码中创建模型:

new TcSet { TechnicalCharacteristic = model, TechnicalCharacteristicID = model.TechnicalCharacteristicID };

您应该使用 Attach() 让 EF 知道它已经存在 object 或者只是从您的数据库中获取实际模型,如下所示:

new TcSet { 
   TechnicalCharacteristic = db.TechnicalCharacteristics.FirstOrDefault(x => x.Id == model.Id), 
   TechnicalCharacteristicID = model.TechnicalCharacteristicID 
};

如果您有 parent 属性 的 ID,最好这样做:

new TcSet { 
       TechnicalCharacteristicID = model.TechnicalCharacteristicID 
    };