Home »

LINQ to SQL: Don't use a Static DataContext

22. April 2009 by Jason 0 Comments

I’ve had this weird bug happening with one of the first apps I wrote using LINQ to SQL, and today, I think I figured out why.  The error has been really random, but always involved in importing data into it.  In this case, they were trying to import Spot (TV Commercial) data into the database, and they kept getting my least favorite LINQ error of all time: “Row not found or changed.”  (Seriously, couldn’t we get something a LITTLE more expressive as an error?  But I digress…)

So today, I decided I would run a SQL Server Profile on it, and trace what was getting thrown at the database.  Glad I did, as I found out that at the end of it trying to insert 10 SPOT records into the database, it was trying to update a CALL (as in telephone call) record repeatedly.  WHY?

Then, I looked at the underlying code, and realized I was using a static DataContext from a Global class.  The problem appears to be that the update never completed, and so anytime I called the SubmitChanges() method on that static DataContext, it was still trying to update the database, and failing.

So, lesson learned?  Don’t use static DataContexts, as they’ll cause you lots of pain and consternation.

blog comments powered by Disqus