I have dilemma about how to organize connection (repository class) to data layer in my application that uses the Entity Framework.
How would you write it? And why?
public class ResearchRepository
{
public Research GetResearch (int id)
{
using (MnijenjeEntities mnijenjeContext = new MnijenjeEntities())
{
ObjectQuery<Research> researchs = mnijenjeContext.Research;
var research = (from r in researchs.Include("SurveyPaper")
where r.ResearchID == id
select r).First();
return research;
}
} //....
OR
public class ResearchRepository
{
private MnijenjeEntities mnijenjeContext;
public Research GetResearch(int id)
{
mnijenjeContext = new MnijenjeEntities();
ObjectQuery<Research> researchs = mnijenjeContext.Research;
var research = (from r in researchs.Include("SurveyPaper")
where r.ResearchID == id
select r).First();
return research;
} //....
The difference is in the dataContext
object usage.
I use more or less the latter technique, but I'm not sure you're asking the right question, precisely. The real question, I think, is "what is the unit of work?" We need to consider some basic facts:
Therefore, I tend to try to use one ObjectContext per unit of work, and dispose of the context when the unit of work is complete. Since a unit of work can potentially involve multiple repositories, I instantiate a Service class which creates the ObjectContext can also return repositories. When I ask the service for a repository, it injects the ObjectContext before returning the new instance. Disposing the service disposes the context and all repositories at once.
I use one service instance per unit of work. In my case, I'm doing ASP.NET MVC, so a unit of work is a response to a single request.