Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# entity framework: correct use of DBContext class inside your repository class

I used to implement my repository classes as you can see below

public Class MyRepository {       private MyDbContext _context;         public MyRepository(MyDbContext context)       {           _context = context;       }        public Entity GetEntity(Guid id)       {           return _context.Entities.Find(id);       } } 

However I recently read this article which says that's a bad practice to have data context as a private member in your repository: http://devproconnections.com/development/solving-net-scalability-problem

Now, theoretically the article is right: since DbContext implements IDisposable the most correct implementation would be the following.

public Class MyRepository {       public Entity  GetEntity(Guid id)       {           using (MyDbContext context = new MyDBContext())           {               return context.Entities.Find(id);           }       } } 

However, according to this other article disposing DbContext would be not essential: http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html

Which of the two articles is right? I'm quite confused. Having DbContext as private member in your repository class can really cause "scalability problems" as the first article suggests?

like image 394
Errore Fatale Avatar asked Oct 09 '15 14:10

Errore Fatale


1 Answers

I think you should not follow the first article, and I will tell you why.

Following the second approach you're loosing pretty much every feature that Entity Framework provides via the DbContext, including its 1st-level cache, its identity map, its unit-of-work, and its change tracking and lazy-loading abilities. That's because in the scenario above, a new DbContext instance is created for every database query and disposed immediately afterwards, hence preventing the DbContext instance from being able to track the state of your data objects across the entire business transaction.

Having a DbContext as a private property in your repository class also has its problems. I believe the better approach is having a CustomDbContextScope. This approach is very well explained by this guy: Mehdi El Gueddari

This article http://mehdi.me/ambient-dbcontext-in-ef6/ one of the best articles about EntityFramework I've seen. You should read it entirely, and I believe it will answer all your questions.

like image 149
Fabio Luz Avatar answered Sep 27 '22 19:09

Fabio Luz