Considering the efficiency of destroying a dataContext and saving it for future db access?

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?

+4
source share
3 answers

I personally use the Unit of Work template along with the repositories for this.

UnitOfWork creates and manages the DataContext. It then passes the context to each repository upon request. Each time the caller wants to perform a new set of database operations, they create a new UnitOfWork.

Interfaces will look something like this:

 public interface IUnitOfWork { IRepository<T> GenerateRepository<T>(); void SaveChanges(); } public interface IRepository<T> where T : class { public IQueryable<T> Find(); public T Create(T newItem); public T Delete(T item); public T Update(T item); } 

This ensures that the lifetime of the context is exactly one unit of work (longer than one operation, but shorter than the lifetime of the application).

+1
source

It is not recommended to carry datacontext with you for a long time. So you are on the right track. It uses the connection pool as far as I know, so the performance hit when creating more than one datacontext in the application life cycle is not too serious.

But I would not create a new instance of the context for every method call of your data class.

I prefer to use it in a unit of work style. In a web application, processing an http request can be considered a unit of work.

So my advice is to create one instance of the datacontext for life in the HTTP request and subsequently dispose of it.

+1
source
0
source

All Articles