问题:为特定客户插入订单的LINQ到实体代码是什么?
更新
以下是一个解决方案(请参阅下面提交的答案之一,以获得更清晰的解决方案):
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();
}
答案 0 :(得分:3)
你的代码并不遥远。只需将第二行更改为如下所示:
Customer customer = ctx.Customer.FirstOrDefault(c => c.FirstName == "Bobby");
if (customer != null)
{
//...
只需将c.FirstName == "Bobby"
替换为可以强烈识别您正在寻找的客户的内容(例如c.Id == customerID
,如果您已经知道ID是什么)。
答案 1 :(得分:3)
请注意,Order有一个Customer属性。您不必将订单添加到客户 - 您可以反过来这样做。因此,不是创建新客户,而是使用Linq获取客户,然后将其添加到新订单。
using (OrderDatabase ctx = new OrderDatabase())
{
ctx.AddOrder(new Order()
{
OrderQuantity = 2,
OrderDescription = "Widgets",
Customer = ctx.Customers.First<Customer>(c => c.CustomerId == yourId)
});
ctx.SaveChanges();
}
答案 2 :(得分:1)
我完全不知道问题所在。
var mycustomer = context.Customers.Where(x => x.id == 100).FirstOrDefault();
if(mycustomer != null)
{
mycustomer.Orders.Add(myorder);
}
context.SaveChanges();
答案 3 :(得分:0)
L2E目前不支持基于集合的操作(不选择更新)。见Use linq to generate direct update without select