通过 WCF 数据服务插入新的父/子
例如,我有一个与地址相关的联系人表。为了与数据库通信,我使用 WCF 数据服务。我有一张表格,其中有联系信息以及可能的地址列表。现在,我创建“要插入的地址”列表并使用插入联系人(此处的上下文是实体数据上下文):
context.AddToContact(contact);
context.SaveChanges();
之后我可以获得插入的 contact.ID 并将其作为父 ID 添加到列表中的所有地址地址:
cacheAddressList.ForEach(a =>
{
address.ContactID = contact.ID;
context.AddToAddress(address);
}
);
context.SaveChanges();
所以我必须执行 2 次插入。
我知道在实体框架中,如果我在子级之间具有导航属性,我可以将子级添加到父级。就我而言,我确实有导航,但这样的代码不起作用(联系人尚未保存..):
context.AddToContact(contact);
cacheAddressList.ForEach(a =>
{
address.Contact = contact;
}
);
context.SaveChanges();
是否可以在此处将所有孩子和父母插入到一笔交易中?因为如果可能的话,我不必创建所有要在父插入后添加的子列表。
For example i have a Contact table that is related to Addresses. To communicate with database i use WCF Data Services. I have a form, where there are contact information with list of possible addresses on it. For now i create list of 'Addresses to insert' and insert Contact using (context is entity data context here):
context.AddToContact(contact);
context.SaveChanges();
After that i can get the inserted contact.ID and add it as a parent id to all addresses in List of Addresses:
cacheAddressList.ForEach(a =>
{
address.ContactID = contact.ID;
context.AddToAddress(address);
}
);
context.SaveChanges();
So i have to do 2 inserts.
I know that in Entity Framework i can add children to parent if i have navigation properties between them. In my case i DO have navigations, but such code doesnt work (contact hasnt been saved yet..):
context.AddToContact(contact);
cacheAddressList.ForEach(a =>
{
address.Contact = contact;
}
);
context.SaveChanges();
Is it possible to insert all children and parents in one transaction here? Because if it is possible-i do not have to create all that lists of children to add after parent insert..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是执行此操作的代码示例:
希望这会有所帮助。
谢谢
普拉蒂克
Here's the code sample to do this:
Hope this helps.
Thanks
Pratik