【发布时间】: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