What’s the best lifetime model for a DataContext? Should I just create a new one whenever I need it (aka, function level), should I keep one available in each class that would use it (class level), or should I create a static class with a static DataContext (app-domain level)? Are there any considered best practices on this?
What’s the best lifetime model for a DataContext ? Should I just create a
Share
You pretty much need to keep the same data context available throughout the lifetime of the operations you want to perform if you’re ever going to be storing changes which are to be
.SubmitChanges()‘d later, as otherwise you will lose those changes.If you’re just querying stuff then it’s fine to create them as needed, but then if later you want to
.SubmitChanges()you’ll have to refactor your code a lot, so you may as well adopt the pattern of effectively keeping thedatacontextglobal throughout your app from the beginning.Note the data context is disconnected. The connection is only made when the query data is enumerated (not when you first run the query, it’s a ‘lazy’ data type so only provides data when it’s needed), and then closed immediately afterwards. On
.SubmitChanges()the connection is opened to submit the changes then closed immediately afterwards. So don’t think keeping thedatacontextaround keeps a connection open, it doesn’t (you can hook theStateChangeevent of the connection to confirm this for yourself, that’s how I’m sure).There is a great article over at Rick Strahl’s Blog which covers this topic in depth, far more than my answer here provides!!