One might want to dispose of the context in some cases.
On the simplistic terms of the OP example, the using
keyword is enough.
So when do we need to use dispose
?
Look at this scenario: you need to process a big file or communication or web-service-contract that will generate hundreds or thousands of BD records.
Adding (+400) thousands or hundreds of entities in EF is a pain for performance: Entity framework performance issue, saveChanges is very slow
The solution is described very well on this site: https://entityframework.net/improve-ef-add-performance
TL;DR - I implemented this and so I ended up with something like this:
/// <summary>
/// Convert some object contract to DB records
/// </summary>
/// <param name="objs"></param>
public void SaveMyList(WCF.MyContract[] objs)
{
if (objs != null && objs.Any())
{
try
{
var context = new DomainDbContext();
try
{
int count = 0;
foreach (var obj in objs)
{
count++;
// Create\Populate your object here....
UserNameItems myEntity = new UserNameItems();
///bla bla bla
context.UserNameItems.Add(myEntity);
// https://entityframework.net/improve-ef-add-performance
if (count % 400 == 0)
{
context.SaveChanges();
context.Dispose();
System.Threading.Thread.Sleep(0); // let the system breathe, other processes might be waiting, this one is a big one, so dont use up 1 core for too long like a scumbag :D
context = new DomainDbContext();
}
}
context.SaveChanges();
}
finally
{
context.Dispose();
context = null;
}
Log.Info("End");
}
catch (Exception ex)
{
Log.Error(string.Format("{0}-{1}", "Ups! something went wrong :( ", ex.InnerException != null ? ex.InnerException.ToString() : ex.Message), ex);
throw ex;
}
}
}