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
The recommended thing to do with a DBContext is to not dispose of it at all (it is the exception to the rule in most cases), even though is a disposable object.
An example of the issue, ths first example is taking a call and evaluation it in the using statement, while the second evaluates it after. (first ons runs, second one throws error The operation cannot be completed because the DbContext has been disposed.
)
List listT;
using (Model1 db = new Model1())
{
listT = db.Tests.ToList(); //ToList Evaluates
}
foreach (var a in listT)
{
Console.WriteLine(a.value);
}
IEnumerable listT1;
using (Model1 db = new Model1())
{
listT1 = db.Tests;
}
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
The same issue happens in
IEnumerable listT1;
Model1 db = new Model1();
listT1 = db.Tests;
db.Dispose();
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
Aslong as you dont open the connection manually you are safe by just using
IEnumerable listT1;
Model1 db = new Model1();
listT1 = db.Tests;
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
and never disposing. as it will take care of itself under most circumstances, as thats what it's designed to do.
Now should you open up a connection by force then the context wont close it automatically when the transfer is done, as it don't know when and then you must/should dispose the object or close the connection and keep the object undisclosed.
Extra midnight reading: