I use LINQ2SQL to handle the needs of my database in ASP.NET MVC 3 . I have a separate model that contains all the access to my database in my class as follows:
public class OperationsMetricsDB { public IEnumerable<client> GetAllClients() { OperationsMetricsDataContext db = new OperationsMetricsDataContext(); var clients = from r in db.clients orderby r.client_name ascending select r; return clients; } public void AddClient(client newClient) { OperationsMetricsDataContext db = new OperationsMetricsDataContext(); db.clients.InsertOnSubmit(newClient); db.SubmitChanges(); }
I have about 50 different methods in this class that everyone creates and then destroys a copy of my DataContext . My reasoning was that this method will save memory, because it will destroy the DataContext after I use the connection and free this memory. However, I feel that it is better to use one instance of the DataContext and keep it open, rather than deleting and reconnecting again and again. eg
public class OperationsMetricsDB { OperationsMetricsDataContext db = new OperationsMetricsDataContext(); public IEnumerable<client> GetAllClients() { var clients = from r in db.clients orderby r.client_name ascending select r; return clients; } public void AddClient(client newClient) { db.clients.InsertOnSubmit(newClient); db.SubmitChanges(); }
What is the best practice?
source share