I am about to embark on a large project using CSLA 3.5/6 and Linq to SQL. However, I wanted to better understand how the CSLA ContextManager works. Joe Rattz (author of Pro LINQ: Language Integrated Query in C# 2008) wrote the following in another forum about the Results Set Cache Mismatch problem associated with long-lived DataContexts:
"DataContexts should be short-lived. How short? As short as possible, yet reasonable. Why? Well, as one of the key Microsoft developers working on LINQ to SQL told me, the data in a DataContext is stale the moment you retrieve it. The reason this is significant has to do with the way data is returned from your query.
I cover this in detail in Chapter 16 of my book, Pro LINQ: Language Integrated Query in C# 2008. Basically what happens is that when you query data from the database with LINQ to SQL, the query is executed in the database to determine which records should be returned. However, if you have already retrieved any of those records with the existing DataContext, instead of returning the record's data from the database, the already retrieved data that is cached inside the DataContext is returned instead. The DataConext determines what data is returned, and this may not match what is currently in the database. In my book, I refer to this as the Results Set Cache Mismatch and I provide an example demonstrating this on pages 504-505. Because of this, it is quite possible to have data returned from a query that does not match the query! I cannot recommend strongly enough to read this portion of my book and understand what is happening.
The issue here is that the longer a DataContext lives, the more cached data it has, and the more likely a resuts set cache mismatch may occur. Therefore, keep your DataContexts short-lived. I would recommend a guideline of something along the lines of using them for a single transaction or SubmitChanges method call. If for some reason I had multiple SubmitChanges method calls in the same function call, I would feel comfortable sharing the DataContext among them. This is a judgement call though, and your situation may be different.
Will sharing a DataContext across calls that occur 5 minutes apart kill you? Probably not. I would not, however, create a DataContext and use it for the life of a long running process."
How is the ContextManager dealing with DataContexts? And, are there any potential issues regarding the above in CSLA?
Thanks for your quick reply.
How does the ContextManager deal with DataContexts? Does it keep them alive for reuse? Or, are they terminated upon completion? If not kept alive, what does the ContextManager do?
Copyright (c) Marimer LLC