Recently when I was working with Entity Framework inside one of our RIA Services end points I ran into the errors below while trying to save my changes. Of course at first this error caused me to stop and scratch my head
To give a bit of background on what I was doing. Inside one of our RIA calls (Off Topic, not a big fan of RIA but this is not the time or the place) we were doing a bit of background processing. In this background processing we needed to query the database for some data (as seen below), update the data and then save the data. However, when I called ObjectContext.SubmitChanges() I would get the error above. what was really odd was that I was saving on the EXACT same ObjectContext instance as the instance the data was queried from so I was a bit stumped.
Here is the original code which was causing the problems
var socialLinks = ObjectContext.SocialMediaLinks.Where( x => x.ClientID == clientId )
As you can see from the line above the code appears to be pretty harmless. I am simply reaching into my ObjectContext and grabbing all the items which match for a given client. Later on in the code I am doing a ForEach loop over the list and changing various values based on rules. However, it is this code which is causing me errors when I try to save.
After a bit of searching and staring it finally occurred to me what the issue was. Because I had never actually ‘completed’ my query the original transaction was still opened and when I called save it was trying to create and use another transaction.
To get around this issue (there may be better ways and if so please let me know) I changed my code to be the code you see below.
var socialLinks = ObjectContext.SocialMediaLinks.Where( x => x.ClientID == clientId ).ToList()
By adding the .ToList() to my query I am forcing the fetch to take place at one time, thus closing the underlying transaction to the database. Now when I saved the data (I literally did not change another line of code) everything worked just fine.
If you find your self in this situation make sure you have actually finished executing your EF queries before you save your changes. BTW this is done inherently when going across the wire which is why I have never seen this before.
Till next time,
12-13-2011 7:13 PM