I am using "Single data context per atomic operation" approach while using Linq to Sql in an ASP.NET MVC application.
So far, I have been using a singleton datacontext, which I learnt has many issues, so I refactored the code to use single datacontext per atomic operation.
An example of a controller action is now as follows (refactoring has not changed this):
public ActionResult List()
{
List<Request> requests = this.repository.AllRequests();
return View(requests);
}
repository is of type IRepository. I want to keep this abstraction to be able to switch to a different data layer (based on my recent experience with Linq to Sql, this may happen very soon :))
The LinqRepository implements the AllRequests() method as follows:
public List<Request> AllRequests()
{
using (DataModelDataContext connection = GetContext())
{
return connection.Requests.ToList();
}
}
(just for reference, previously DataContext instance was a field of the LinqRepository and LinqRepository was held as a single static instance)
The DataContext is disposed before the method returns.
The view code now throws ObjectDisposed exceptions when accessing deferred properties:
<%= Html.Encode(request.Branch.Name) %> //throws
I learnt disposing of the DataContext may not be needed (here http://stackoverflow.com/questions/389822/when-should-i-dispose-of-a-data-context)
When I do not dispose the DataContext (remove the using), there is no ObjectDisposedException.
i.e.: I altered the method as follows:
public List<Request> AllRequests()
{
DataModelDataContext connection = GetContext();
return connection.Requests.ToList();
}
But I am wondering, what are the implications of not disposing DataContext instance in this scenario?
I know I am supposed to read all the data from the entity instance (including deferred properties) before the DataContext is disposed, but I would not like to introduce another abstraction (another Request class, copying all the properties over to it).
My questions:
Does the entity object hold a strong reference to its parent DataContext, preventing it from being GC-ed? (I guess it does, juts want to be 100% sure)
Can you provide advice on recommended approaches when using Linq to Sql while data layer abstraction needs to be retained? (including partial property updates)
Is there an open source project using a repository abstraction implementing Linq to Sql in ASP.NET MVC?