简体   繁体   English

使用EF4 POCO将实体附加到ObjectContext而没有相关实体

[英]Attaching entity to ObjectContext without related entities with EF4 POCO

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 (eg name has been changed) 标签已被修改(例如名称已更改)

So I was thinking that I could somehow attach only the product to a new ObjectContext and save changes. 所以我在想我可以以某种方式仅将产品附加到新的ObjectContext并保存更改。 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. 当然,我可以附加图形,然后手动分离除所涉及产品之外的所有其他实体,但这是一个可怕的解决方案,我希望找到另一个。

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. 您将必须将新的时间戳记从克隆复制回原始实体,否则将无法再次保存原始实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM