Question: what is the LINQ-to-Entity code to insert an order for a specific customer?
Update
Here is the a solution (see one of the submitted answers below for a much cleaner solution):
using (OrderDatabase ctx = new OrderDatabase())
{
// Populate the individual tables.
// Comment in this next line to create a new customer/order combination.
// Customer customer = new Customer() { FirstName = "Bobby", LastName = "Davro" };
// Comment in this line to add an order to an existing customer.
var customer = ctx.Customers.Where(c => c.FirstName == "Bobby").FirstOrDefault();
Order order = new Order() { OrderQuantity = "2", OrderDescription = "Widgets" };
// Insert the individual tables correctly into the hierarchy.
customer.Orders.Add(order);
// Add the complete object into the entity.
ctx.Customers.AddObject(customer);
// Insert into the database.
ctx.SaveChanges();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…