Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

c# - How do I use LINQ-to-Entities to insert data into a specific table?

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

enter image description here

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();                        
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...