添加/更新子和父记录同时 [英] Adding/updating child and parent record same time
问题描述
可有人请告诉我创建/更新在同一时间(如客户有多个地址)与至少一个家长和孩子记录或没有code尽可能最简单的方法? Web窗体和MVC中。
Can someone please show me the easiest way to create/update a parent and child record at the same time (like customer with multiple addresses) with least or no code as possible? Both Web Forms and in MVC.
推荐答案
基本的想法是创建/更新父记录并返回新的ID(键)。然后使用该密钥创建相关的子记录。例如,假设你有一个事件表和相关EventDates表:
The basic idea would be to create/update the parent record and return the new ID (key). Then use that key to create the related child records. For example, say you have an Events table and a related EventDates table:
public static int CreateEvent(
out int eventId,
DateTime datePosted,
string title,
string venue,
string street1,
string city,
string state,
string zipCode)
{
...
}
public static void AddEventDates(
int eventDateID,
int eventID,
DateTime startDate,
DateTime endDate)
{
...
}
在这里保持数据的完整性是非常重要的;如果其中一个更新失败,则既需要返回到原来的状态。你可以这样实现自己或使用事务:
It's important to maintain data integrity here; if one of the updates fails then both need to be returned to the original state. You could implement this yourself or use transactions:
http://msdn.microsoft.com/ EN-US /库/ z80z94hz%28VS.90%29.aspx
这篇关于添加/更新子和父记录同时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!