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

前端 未结 4 1606
自闭症患者
自闭症患者 2020-12-11 21:28

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

\"enter

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 21:56

    Notice that Order has a Customer property. You don't have to add the Order to the Customer -- you can do it the other way around. So, instead of creating a new Customer, get the Customer using Linq, then add it to your new Order.

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

提交回复
热议问题