Add a child to tables When a parent is saved in context

I updated the EntityFramework objectContext to the latest version of DBContext v6.1.3 for my MVC web application. It uses the DataBase First approach

There is a script to add the ordering process to the database using EDMX. The code behavior below will add objects to each child table, only keeping the object of the parent table in context. This worked great in ObjectContext. [Each table has a new record [Order, OrderDetail, license]

But after upgrading to DBContext, the code below only added an entry to the [Order] parent table. Tables for children have a blank entry. Here I have over 10 child tables for the order process. For example, a few mentions. Please suggest a way to solve the problem.

Table

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

the code

 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();
}

    }
+4
source share
2 answers

When you use ObjectContextyour objects probably were not POCO and derived from EntityObjectthat automatically provides traceability between Orders, and data associated with it ( Licenseand OrderDetails) so you do not need to explicitly add OrderDetailsand Licensein context.

, DbContext, EF License OrderDetails, :

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

, ( , OrderDetails - - ), EF :

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, , .

+3

, .

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

Source: https://habr.com/ru/post/1598819/


All Articles