如何使用LINQ到实体将数据插入到特定的表? [英] How do I use LINQ-to-Entities to insert data into a specific table?

查看:151
本文介绍了如何使用LINQ到实体将数据插入到特定的表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:?什么是LINQ到实体代码中插入的顺序为具体客户





更新



下面是一个解决方案(请参见下面的提交答案为更清洁的解决方案之一):

 使用(OrderDatabase CTX =新OrderDatabase())
{
//填写个人表格。

//在这个在下一行注释创建一个新的客户/订单组合。
//客户的客户=新客户(){名字=波比,姓氏=Davro};在此行中
//注释命令添加到现有的客户。
VAR的客户= ctx.Customers.Where。(C = GT; c.FirstName ==巴比)FirstOrDefault();

订购订购=新订单(){OrderQuantity =2,OrderDescription =部件};

//将各个表到正确的层次结构。
customer.Orders.Add(订单);

//添加完整的对象变成实体。
ctx.Customers.AddObject(客户);

//插入到数据库中。
ctx.SaveChanges();
}


解决方案

您的代码并不遥远关闭。只要改变你的第二个行如下:

 客户客户= ctx.Customer.FirstOrDefault(C => c.FirstName ==巴比); 
如果(客户!= NULL)
{
// ...

只需更换 c.FirstName ==巴比的东西,可以强烈认同你正在寻找(如 c中的客户.ID ==的customerID 如果你已经知道的ID是什么)。


Question: what is the LINQ-to-Entity code to insert an order for a specific customer?

Update

Here is the a solution (see one of the submitted answers below for a much cleaner solution):

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

解决方案

Your code isn't far off. Just change your second line to read as follows:

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

Just replace the c.FirstName == "Bobby" with something that can strongly identify the customer you're looking for (e.g. c.Id == customerID if you already know what the ID is).

这篇关于如何使用LINQ到实体将数据插入到特定的表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆