Câu hỏi: mã LINQ-to-Entity là gì để chèn một đơn đặt hàng cho một khách hàng cụ thể?Làm cách nào để sử dụng LINQ-to-Entities để chèn dữ liệu vào một bảng cụ thể?
Cập nhật
Đây là một giải pháp (xem một trong những câu trả lời dưới đây gửi cho một giải pháp sạch hơn nhiều):
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();
}
Tất nhiên, tôi có thể sử dụng ADO.NET để thực hiện công việc - nhưng tôi không muốn "gây ô nhiễm" mô hình của mình bằng cách xử lý khóa chính/khóa ngoài. Lưu ý rằng đoạn mã trên không có khóa chính/khóa ngoài - LINQ to Entities xử lý điều này cho tôi. – Contango