We are using entity framework for communication with database in our WCF service methods, recently we run the code review tool on our service code. As usual we got many review p
There is no need to explicitly dispose DbContext.
This is an old hold over from pre-DbContext tools. DbContext is managed code and optimistically maintains database connections on its own. Why sledgehammer it? Whats the hurry? Why not just let the garbage collector decide the best time to clean up when the machine is idle or in need of memory? Also refer to this post: https://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/
By not worrying about having to dispose will simplify and optimize your code. Typically I might inherit from a database "helper" class to where I use a getter to either return an already existing DbContext instance, or instantiates a new instance. .
public class DataTools
{
private AppContext _context;
protected AppContext Context => _context ?? (_context = new AppContext());
}
pubic class YourApp : DataTools
{
public void DoLotsOfThings()
{
var = Context.SomeTable.Where(s => s.....);
var stuff = GetSomeThing();
foreach(){}
}
Public string GetSomething()
{
return Context.AnotherTable.First(s => s....).Value;
}
}