开发者

Adding existing entity to navigation property of a different entity

I'm using EF4 and I'm running into a problem when I try to do something that looks quite trivial to me.

I have two entities, let's call them A and B. These entities have a many-to-many association between them with a navigation property on A that contains a list of related B entities开发者_Go百科.

What I want to do is to add existing B entities to a new A entity. When I try to do that, I get an exception:

AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.

Has anyone run into such a problem?

More info that might be relevant:

  • I've created the DB from the model.
  • I have a base entity that both A and B entities inherit from.

Update: Found a solution - detach the linked entity and re-attach it to the context, then everything goes as planned.


I had a similar problem today. In my case my table was a view and I had addded a stored procedure for the InsertFunction. Trouble was that I did not confiugre result bindings from my stored procedure. The symptom was that I could add a single entity fine but got an "key values conflict" exception when adding multiple entities.

Once I made the stored procedure return the new ID (key) and then configured the EF's result biding all was fine.

To the end of the stored procedure add something like this:

select SCOPE_IDENTITY() as NewWidgetId

In the EF config set the result binding:

NewWidgetId -> WidgetId : <widget's type>

I found this site helpful: Using Stored Procedures for Insert, Update & Delete in an Entity Data Model

Hope this helps

Rob Smyth

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜