views:

103

answers:

1

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.

+1  A: 

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:

  • Using multiple ObjectContexts for the same operation is considerably more difficult than using a single ObjectContext in one operation.
  • Keeping an ObjectContext around for a long time can potentially consume a lot of memory, and may have other undesirable side effects.
  • The ObjectContext itself has some "lightweight transaction" features, namely that it accumulates changes and can apply them all at once, and that you are, to some degree, isolated from changes in other contexts.

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.

Craig Stuntz