【问题标题】:How do I use LINQ-to-Entities to insert data into a specific table?如何使用 LINQ-to-Entities 将数据插入特定表?
【发布时间】: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


【解决方案1】:

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

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

只需将 c.FirstName == "Bobby" 替换为可以强烈识别您正在寻找的客户的名称(例如,c.Id == customerID,如果您已经知道 ID 是什么)。

【讨论】:

  • 太棒了,这很好用。当您首先正确回答时,我必须将答案奖励给您。非常非常感谢!
【解决方案2】:

注意 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();
}

【讨论】:

  • 请注意,您可以将选择客户的条件替换为任何其他相关条件;如果您想根据其他条件进行搜索,则不需要 yourId 来拥有 CustomerId。
【解决方案3】:

我不明白到底是什么问题。

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

【讨论】:

    【解决方案4】:

    L2E 目前不支持基于集合的操作(不选择更新)。见Use linq to generate direct update without select

    【讨论】:

    • 我不认为他在没有选择的情况下要求更新。他提到了一个 LINQ 查询来首先检索正确的客户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    相关资源
    最近更新 更多