【发布时间】:2011-02-07 21:03:56
【问题描述】:
问题:为特定客户插入订单的 LINQ-to-Entity 代码是什么?
更新
这是一个解决方案(有关更简洁的解决方案,请参阅下面提交的答案之一):
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();
}
【问题讨论】:
-
当然,我可能会使用 ADO.NET 来完成这项工作——但我不想通过处理主键/外键来“污染”我的模型。请注意,上面的代码没有主键/外键 - LINQ to Entities 为我处理。
标签: c# linq linq-to-entities