使用 EF4 POCO 将实体附加到没有相关实体的 ObjectContext
示例:加载一个产品实体,包括其标签不跟踪:
repository.Product
.Include("Tag")
.Where(p => p.ProductID == 1)
.Execute(MergeOption.NoTracking);
请注意,这是一个多对多关系;一个产品可以有多个标签,并且标签可以与多个产品相关联。
在其他地方,我想保存对产品实体所做的任何更改,但不保存对其相关标签或其与这些标签的关系所做的更改。
这意味着,这些更改都不能保存:
- 标签已从产品中删除
- 标签已添加到产品
- 标签已被修改(例如名称已更改)
所以我想我可以以某种方式附加 仅将产品添加到新的 ObjectContext 并保存更改。但由于某种原因,我无法弄清楚如何仅将单个实体而不是整个图形附加到对象上下文。
当然,我可以附加图表,然后手动分离除相关产品之外的所有其他实体,但这是一个可怕的解决方案,我希望找到另一个解决方案。
Example: a product entity is loaded including its tags without tracking:
repository.Product
.Include("Tag")
.Where(p => p.ProductID == 1)
.Execute(MergeOption.NoTracking);
Note that this is a many-to-many relationship; a product can have several tags, and tags can be associated with several products.
Somewhere else, I want to save any changes made to the product entity, but without saving changes made to its related tags or its relationship with these tags.
Meaning, neither of these changes may be saved:
- A tag has been removed from the product
- A tag has been added to the product
- A tag has been modified (e.g. name has been changed)
So I was thinking that I could somehow attach only the product to a new ObjectContext and save changes. But for some reason I can't figure out how to only attach a single entity to the object context, and not the entire graph.
Of course, I could attach the graph and then manually detach all other entities except the product in question, but this is a horrible solution, and I was hoping to find another.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试克隆您的产品(不是深度克隆!),附加克隆并保存更改。您的原始对象图将保持分离。唯一的问题可能是如果您使用时间戳之类的东西来进行并发处理。您必须将新时间戳从克隆复制回原始实体,否则您将无法再次保存原始实体。
You can try to make a clone of your Product (not deep clone!), attach the clone and save changes. Your original object graph will remain detached. The only problem can be if you are using something like timestamp for concurrency handling. You will have to copy new timestamp from clone back to original entity otherwise you will not be able to save original entity again.