如何使用linq to sql将数据插入一对多关系

时间:2017-05-01 12:12:08

标签: c# sql-server linq

如何使用linq to sql将数据插入一对多关系。我有两个表首先是人,其次是订单,我在两个表之间建立关系,我想一次向两个表插入数据

public ActionResult Add(CustomerViewData data)
    {
        string message = "";
        var item = data.Customer;

        try
        {
            _repositoryCustomer.Insert(item);
            _repositoryCustomer.Save();
            return RedirectToAction("Edit", new { message = Constants.RecordSaved, id = item.CustomerId});

        }
        catch (Exception ex)
        {
            message = "Customer had error saving.";
            Log.Error(message, ex);
        }
        return View("Edit", new CustomerViewData { PageMode = PageMode.Add, Message = message });
    }

1 个答案:

答案 0 :(得分:0)

using (MyDataContext dc = new MyDataContext())
{
  Person p = new Person();
  Order o = new Order();
  p.Orders.Add(o); //connect the objects into an object graph.

  dc.Persons.Add(p); //add the graph to the data context
  dc.SubmitChanges();  //save it all.
}