Thursday, January 29, 2009

More Linq2Entities From The Real World

I've built a WCF service that takes as a parameter an entity object with a reference to another entity (a foreign key-primary key relationship). When I try adding it to the database (context object) with LINQ, I get the following exception:

The object cannot be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key.

I tried manually attaching the entity reference, but that didn't seem to work either so I finally had to get the primary key value of the reference, re-fetch the object from the database and set the reference again with the newly-retrieved object.

They make this so much harder than it should be :-(

No comments: