Monday, April 23, 2012

Entity Framework and Saving Objects


I came across a new problem today with entity framework - In one of our projects at AIS, we use a repository to perform data manipulation. We have one function to get the user from the user id, something like:

// first open entities then
return entities.Users.SingleOrDefault(k => k.UserId == userId);

We also have another repository function to save that accepts a user as a param, opens entities, and calls a entities.SaveChanges() on the user. My first reaction was to get the user from the repository, make changes to the needed fields, and then pass the user to the save function.

Unfortunately, Entity Framework did not seem to like saving an existing entity object, and complained loudly, returning:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
It took me a while to find, but the solution seemed to be relatively easy - I just needed to detach the object after the initial selection:

// first open entities then
var result = entities.Users.SingleOrDefault(k => k.UserId == userId);
entities.Detach(result);

return result;

Eventually, this problem may be solved by refactoring the repository to use a single entities object, instead of creating the entity object in each call, but this works for now.

No comments :

Post a Comment