views:

49

answers:

1

I am building an ASP.NET 4.0 MVC 2 app with a generic repository based on this blog post.

I'm not sure how to deal with the lifetime of ObjectContext -- here is a typical method from my repository class:

public T GetSingle<T>(Func<T, bool> predicate) where T : class
{
    using (MyDbEntities dbEntities = new MyDbEntities())
    {
        return dbEntities.CreateObjectSet<T>().Single(predicate);
    }
}

MyDbEntities is the ObjectContext generated by Entity Framework 4.

  1. Is it ok to call .CreateObjectSet() and create/dispose MyDbEntities per every HTTP request? If not, how can I preserve this object?
  2. If another method returns an IEnumerable<MyObject> using similar code, will this cause undefined behavior if I try to perform CRUD operations outside the scope of that method?
+2  A: 

Yes, it is ok to create a new object context on each request (and in turn a call to CreateObjectSet). In fact, it's preferred. And like any object that implements IDisposable, you should be a good citizen and dispose it (which you're code above is doing). Some people use IoC to control the lifetime of their object context scoped to the http request but either way, it's short lived.

For the second part of your question, I think you're asking if another method performs a CRUD operation with a different instance of the data context (let me know if I'm misinterpreting). If that's the case, you'll need to attach it to the new data context that will perform the actual database update. This is a fine thing to do. Also, acceptable would be the use the Unit of Work pattern as well.

Steve Michelotti
yep, exactly what i do. StuctureMap httpcontextscoped service/repo/datacontext.
RPM1984
I am using .CreateObjectSet() because I can't obtain a reference to the sets created by EF, for example dbEntities.Products or dbEntities.Orders. Is .CreateObjectSet() the only way to get a handle to one of these collections?
Alex