【问题标题】:Add child object to tables When parent object saved into context将子对象添加到表中 当父对象保存到上下文中时
【发布时间】:2023-03-26 20:13:01
【问题描述】:

我已为我的 MVC Web 应用程序将 EntityFramework objectContext 升级到 DBContext 最新版本 v6.1.3。这里使用了DataBase First方法

有使用 EDMX 将订单流程添加到数据库的场景。当仅将父表对象保存到上下文中时,以下代码行为将在每个子表中添加对象。这在 ObjectContext 中完美运行。[每个表都有新条目[Order,OrderDetail,license]

但是升级到 DBContext 后,下面的代码只在父表 [Order] 中添加了条目。子表有空记录。在这里,我有 10 多个用于订单处理的子表。例如,仅提及少数。请提出解决问题的方法。

表格

Order -parent table
OrderDetail -child table of Order
License- child table of Order

代码

 using (DBEntities contextentity = new DBEntities ())
                {
 using (TransactionScope transaction = new TransactionScope())
                        {
//Parent table
                    Orders order = new Orders();
                    order.customerid = 1232;                  
                    order.OrderDate = DateTime.Now;

//Child table
               OrderDetails orderDetails = new OrderDetails();
               orderDetails.Orders = order; //linked parend table
               orderDetails.ProductID = 1233;
               orderDetails.Quantity = 3;
               orderDetails.UnitPrice = product.UnitPrice;

//child table
 License license = new License();
  license.ProductID = 1233;
  license.CustomerId= 1232;                                       
  license.LastModifiedDate = DateTime.Now;
  license.Orders = order; // linked the parent 

//Add the parent table in to context
  contextentity.Orders.Add(order);                         
contextentity.SaveChanges();
 transaction.Complete();
}

    }

【问题讨论】:

    标签: asp.net-mvc entity-framework entity-framework-6 dbcontext


    【解决方案1】:

    当您使用ObjectContext 时,您的实体可能不是POCO,而是派生自EntityObject,它自动提供Orders 及其相关数据(LicenseOrderDetails)之间的跟踪功能,所以您没有'不必显式地将orderDetailslicense 添加到上下文中。

    但是,当您切换到DbContext 时,EF 不再能够自动检测到licenseorderDetails,因此您必须明确添加它们:

    contextentity.OrderDetails.Add(orderDetails);
    contextentity.Licenses.Add(license);
    

    或者,如果您将直接在根对象中公开关系(您应该这样做,因为 orderDetails - 作为值对象 - 不应该直接添加到上下文中)EF 将 em> 能够检测到依赖关系,您不必显式添加它们:

    public class Orders
    {
        // assuming each order has many lines
        public virtual ICollection<OrderDetails> OrderLines { get; set; }
    
        // assuming each order has many licenses
        public virtual ICollection<License> Licenses { get; set; }
    
        // rest of your order data
    }
    

    还有连接:

    order.OrderLines.Add(orderDetails);
    order.Licenses.Add(license);
    

    现在(一旦保存),子对象的Orders 导航属性也将正确指向父实体,因此您不必手动设置它们。

    【讨论】:

    • 嗨,Haim,很好的解决方案。
    【解决方案2】:

    我认为您必须将每个实体添加到其表中。尝试在保存更改之前添加这些行

    contextentity.OrderDetails.Add( orderDetails );
    contextentity.Lisences.Add( license );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2018-10-18
      相关资源
      最近更新 更多