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

4
问题:如何使用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会为我处理这个问题。 - Contango
4个回答

3

请注意,订单具有客户属性。您不必将订单添加到客户中--您可以反过来做。因此,不要创建新的客户,使用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();
}

1
请注意,您可以更改条件以选择客户,而不必使用您的ID作为客户ID来搜索其他标准。 - Andrew

3

你的代码已经很接近了。只需将第二行更改为以下内容:

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

只需将 c.FirstName == "Bobby" 替换为能够强烈识别您要查找的客户的内容(例如,如果您已经知道ID,则使用 c.Id == customerID )。


1
太棒了,这个很好用。我必须把答案授予你,因为你第一个回答正确。非常感谢! - Contango

1

我不确定问题是什么,确切地说。

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

0

1
我认为他并不是要求在没有选择的情况下进行更新。他提到了使用LINQ查询来首先检索正确的客户。 - Justin Morgan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接