如何使用LINQ-to-Entities将数据插入特定表?

问题:为特定客户插入订单的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(); } 

你的代码并不遥远。 只需将第二行更改为如下所示:

 Customer customer = ctx.Customer.FirstOrDefault(c => c.FirstName == "Bobby"); if (customer != null) { //... 

只需用能够强烈识别您正在寻找的客户的东西替换c.FirstName == "Bobby" (例如,如果您已经知道ID是什么, c.Id == customerID )。

请注意,Order具有Customer属性。 您无需将订单添加到客户 – 您可以反过来执行此操作。 因此,不是创建新客户,而是使用Linq获取客户,然后将其添加到新订单中。

 using (OrderDatabase ctx = new OrderDatabase()) { ctx.AddOrder(new Order() { OrderQuantity = 2, OrderDescription = "Widgets", Customer = ctx.Customers.First(c => c.CustomerId == yourId) }); ctx.SaveChanges(); } 

我完全不知道问题所在。

 var mycustomer = context.Customers.Where(x => x.id == 100).FirstOrDefault(); if(mycustomer != null) { mycustomer.Orders.Add(myorder); } context.SaveChanges(); 

L2E当前不支持基于集合的操作(不选择更新)。 请参阅使用linq生成直接更新而不选择