I’m currently writing a data access layer for an application. The access layer makes extensive use of linq classes to return data. Currently in order to reflect data back to the database I’ve added a private data context member and a public save method. The code looks something like this:
private DataContext myDb; public static MyClass GetMyClassById(int id) { DataContext db = new DataContext(); MyClass result = (from item in db.MyClasss where item.id == id select item).Single(); result.myDb = db; return result; } public void Save() { db.SubmitChanges(); }
That’s a gross over simplification but it gives the general idea. Is there a better way to handle that sort of pattern? Should I be instantiating a new data context every time i want to visit the db?
It actually doesn’t matter too much. I asked Matt Warren from the LINQ to SQL team about this a while ago, and here’s the reply:
But basically you don’t really need to dispose of them in most cases – and that’s by design. I personally prefer to do so anyway, as it’s easier to follow the rule of ‘dispose of everything which implements IDisposable’ than to remember a load of exceptions to it – but you’re unlikely to leak a resource if you do forget to dispose of it.