EF插入相关对象
我在实体框架上使用 silverlight 客户端和 ado.net dataservices。
我有一个实体联系人和一个与外键关系相关的实体地址... 一个联系人可以有 1 个或多个地址,但一个地址始终需要至少 1 个联系人。 非常基本...
我有一个用于我的联系人和地址的存储库,其中有一个方法添加(T 实体),...
在我的客户端上,我有一个表单,允许用户添加带有地址的联系人
,我想保存两者保存到数据库...
Address a = new Address();
a.Street="Street",
a.City = "City"
a.Contact =
new Contact(){ Name="Name",Age="60"}
_repository.Add(a);
....
好吧,我发现我无法立即保存相关的对象图,所以我做了类似的事情,
DataBaseEntities.AddToContact(obj2Badded.Contact);
DataBaseEntities.AddToAddress(obj2Badded);
DataBaseEntities.SetLink(obj2Badded,"Contact",object2Badded.Contact);
DataBaseEinties.BeginSaveChanges(...)
是否可以在未添加联系人时执行此操作,地址也不会被添加,反之亦然。反之亦然...
...我所尝试的所有方法都不起作用...
如果有人能在这个主题上为我指出正确的方向,那就太好了我只想添加一个相关的对象图=} ...
I am using silverlight client with ado.net dataservices on entity framework.
I have an Entity Contact and an Entity Address which is related with a foreign key relation ship...
A contact can have 1 or more Adresses but a Address needs always at least 1 contact..
pretty basic...
I have a Repository for my contacts and Address which has a Method Add(T entity),...
On my Client I have a form with allows users to add a contact with an address
and I want to save both away to the database...
Address a = new Address();
a.Street="Street",
a.City = "City"
a.Contact =
new Contact(){ Name="Name",Age="60"}
_repository.Add(a);
....
Ok i figured out that I can not save a related object graph right away so i did something like this
DataBaseEntities.AddToContact(obj2Badded.Contact);
DataBaseEntities.AddToAddress(obj2Badded);
DataBaseEntities.SetLink(obj2Badded,"Contact",object2Badded.Contact);
DataBaseEinties.BeginSaveChanges(...)
Is there away to do this in transations like when contact is not added address will also not be added and vice versa...
... and all what I have tried is not working...
It would be great if someone can point me in the right direction on this topic I simply want to add a related object graph =} ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的第一个示例应该可以正常工作,相关实体等等。 如果您要为这两个实体插入新对象,则无需单独将相关实体添加到上下文中。 因此,除非您告诉我们运行此代码时出现的问题,否则很难提供帮助。
Your first example should work just fine, related entities and all. There is no need to add related entities to the context separately, if you are inserting new objects for both of them. So unless you tell us what the problem is when you ran this code, it will be hard to help.
的内容后,它对我有用。
我遇到了类似的问题,在添加类似之前
如果您在项目中包含 edmx 并使用 ObjectContext,则不需要,但如果您创建服务引用并使用生成的 DataServiceContext,则需要它。
I had a similar problem and it worked for me after adding something like
just before
This isn't needed if you include the edmx in your project en use the ObjectContext, but it is needed if you create a Service reference and use the generated DataServiceContext.