4

I'm using MVC .Net. Usually I always use something like below to create one instance whenever I need to query the DB:

using (EntitiesContext ctx = new EntitiesContext())
{
    ....
}

Then I see lots of sample codes that always have one instance of DBContext in the controller, use it whenever needed, and Dispose it when the controller is Disposed.

My question is: which one is the right way to use it? Any advantage/disadvantage? Maybe, is there any performance difference?

Thanks

urlreader
  • 6,319
  • 7
  • 57
  • 91

1 Answers1

3

Using a context by controller instance has multiple advantages :

  • It's scoped to the controller, therefore if you need it multiple times you allocate only one instance
  • EntityFramework use local caching, then if you query multiple times over the same DbSet with the same parameters, it will match those entities in cache instead of querying the database
  • If you use the repository pattern, it's a good practice to share your context accross repositories. That way, each repository is able to see what as been done by other repositories if you manipulate multiple repository in the same controller scope

From the Getting Started with ASP.NET 5 and Entity Framework 6 , you can read :

Context should be resolved once per scope to ensure performance and ensure reliable operation of Entity Framework.

See a related SO post that deeply explain why it's better to use this approach.

Community
  • 1
  • 1
Fabien ESCOFFIER
  • 4,751
  • 1
  • 20
  • 32