将子对象添加到表时将父对象保存到上下文中

时间:2015-07-21 06:05:44

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

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

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

但升级到DBContext后,下面的代码只在Parent表[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();
}

    }

2 个答案:

答案 0 :(得分:3)

当您使用ObjectContext时,您的实体可能不是POCO并且来自EntityObject,它会自动提供Orders及其相关数据之间的跟踪功能({{1} }}和License)因此您无需在上下文中明确添加OrderDetailsorderDetails

但是,当您切换到license时,EF无法再自动检测到DbContextlicense,因此您必须明确添加它们:

orderDetails

或者,如果你直接在根对象中公开关系(正如你应该的那样,因为contextentity.OrderDetails.Add(orderDetails); contextentity.Licenses.Add(license); - 作为一个值对象 - 不应该直接添加到上下文中)EF 能够检测到依赖关系,您不必明确添加它们:

orderDetails

连接:

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); 导航属性也会正确指向父实体,因此您不必手动设置它们。

答案 1 :(得分:1)

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

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