ChangeRelationshipState方法不支持使用外键值定义的关系The ChangeRelationshipState method is not supported for relationships that are defined by using foreign-key values

- 此内容更新于:2015-01-06
主题:

原文:

In EF 6, to remove entities from a collection without actually fetching the collection, I am using:

manager.ChangeRelationshipState(entity, wrappedIdOfRelatedEntity, e => e.Collection, EntityState.Deleted);

It works for M:N relationships. But in case of 1:N, it throws the following error:

The ChangeRelationshipState method is not supported for relationships that are defined by using foreign-key values.

Just to clarify, I do not want to fetch the collection, since it may be really huge, moreover I do not want to fetch the entities that should be removed.

I have the key (id) of the entity that 'contains' the collection and keys (ids) of the entities that should be removed.

Any hints, how to do it correctly?

NOTICE: Adding is possible by just adding wrapped entity keys to a collection. But removing is causing the problem.

解决方案:
原文:

Do you use row versioning/timestamp on your entities? If you do, EF needs to version because it's doing to send an update statement containing both the id and version of the entity to delete.

If you're not using row versioning/timestamp on your entities, you can do the following using the DbContext API but you need to use proxies and change detection.

  1. Recreate the entities you want to remove from the collection by using DbSet.Create
  2. Populate the recreated entities with the id of the entities you want to remove
  3. Attach the entities using DbSet.Attach
  4. Add the entities to the collection and then call AcceptAllChanges on the ObjectContext to reset the state of the entites
  5. Remove the entities from the collection
  6. Call save changes and it should issue update statements to remove the entities from the collection.

If you're using row versioning/timestamp on your entities, you can use the steps above, but in step 2, you need to set both the version and the id.

TN.的回复:我不能叫AcceptAllChanges,因为我做的多变化。是否可以接受更改每一个集合?

(原文:I cannot call AcceptAllChanges, since I am doing multiple changes at once. Is it possible to accept changes just per a single collection?)

hjb417的回复:你能做重放(步骤1 - 4)之前您的更改吗?

(原文:can you do the replay (steps 1-4) before making your changes?)

TN.的回复:这将使代码非常复杂,因为它是一个& # 39;api # 39;函数,它可以称为地方(例如,在一个复杂的事务)。

(原文:This would make the code really complex, since it is a 'API' function, which could be called anywhere (e.g. in a complex transactions).)