Sam
Sam

Reputation: 15761

Entity Framework Context?

I am really having a hard time trying to figure out where the EF Context is managed in an MVC app.

I am using the Service/Repository/EF approach and was playing with the UnitOfWork pattern with a context inside of it, and then using it inside the controller actions to utilize various services. It works, but by doing this, I am making the controllers dependent on EF right?

Any suggestions?

Upvotes: 2

Views: 597

Answers (3)

PHeiberg
PHeiberg

Reputation: 29801

If you rely upon abstractions and create an IUnitOfWork and IRepository encapsulating the EF Context the Controller would be dependent on the abstractions and not any concrete implementation.

The repository and unit of work themselves are the only classes that would be dependent on Entity Framework or whatever ORM you are using.

public class MyController : Controller
{
  public MyController(IRepository r1, IRepository r2, IUnitOfWork uow)
  { ... }

  [HttpPost]
  public ActionResult SomeAction(Model data)
  {
    _r1.DoSomeChangesToEntities(data);
    _r2.DoSomeChangesToEntities(data);
    _uow.SaveChanges();
    return View(...);
  }
}

Edit as per request:

A simple Unit Of Work implementation could be:

public class EFUnitOfWork : IUnitOfWork
{
  private DataContext _context;

  public EFUnitOfWork(DataContext context)
  {
    _context = context;
  }

  public void Commit()
  {
    _context.SubmitChanges();
  } 
}

You would of course make sure that your services/repositories use the same context as the Unit of Work by injecting the same context into them.

Upvotes: 1

Shiju
Shiju

Reputation: 1313

Check out the sample code at http://efmvc.codeplex.com/

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

That depends on what you meant "making controller dependent on EF"?

Do you use any EF related class in controllers? If not they are obviously not dependent on EF and you can easily swap your repositories and unit of work for other implementation (for example using NHibernate).

But yes whole your asp.net mvc application is dependent on EF if you are using it in any layer - it will simply not run without loading EF dlls.

Upvotes: 0

Related Questions