LINQ to SQL - 当插入一行(以及其他几行FK指向此行的PK)时,执行[context]是否足够。[MainTable] .InsertOnSubmit(row),或者我还需要为其他行调用它吗?
这是一个精简代码示例(C#):
//Forgive the contrived example (off the top of my head) :)
//Main row
Order order = new Order
{
itemId = (int) data["itemNumber"],
address = (string) data["address"]
};
db.Orders.InsertOnSubmit(order); //would be nice to only have to submit here.
//Related rows
OrderPerson orderPerson = new OrderPerson
{
Order = order,
//other things, etc.
orderRoleId = RoleIds.Customer
};
//Q: need to do "db.OrderPerson.InsertOnSubmit(orderPerson);" here?
OrderHistoryEntry historyEntry = new OrderHistoryEntry
{
Order = order,
//other things, etc.
historyTypeId = HistoryIds.Ordered
};
//Q: need to do "db.OrderHistoryEntry.InsertOnSubmit(historyEntry);" here?
db.SubmitChanges();
是否足以执行:db.Orders.InsertOnSubmit(order);
或者是否还需要为相关行执行InsertOnSubmit(orderPerson和historyEntry)?
只在主行上运行一次会很不错。 MSDN示例就是这样,但它们都有相反的关系(引用主行中的其他行)。
感谢您的想法。
答案 0 :(得分:4)
相反怎么样?
Order order = new Order
{
itemId = (int) data["itemNumber"],
address = (string) data["address"]
};
OrderPerson orderPerson = new OrderPerson
{
orderRoleId = RoleIds.Customer
};
order.OrderPersons.Add(orderPerson);
OrderHistoryEntry historyEntry = new OrderHistoryEntry
{
historyTypeId = HistoryIds.Ordered
};
order.OrderHistoryEntries.Add(historyEntry);
db.Orders.InsertOnSubmit(order);
db.SubmitChanges();