I am attempting to encrypt some data where my table has half a million records. Inspired by the answer here - Fastest Way of Inserting in Entity Framework - I attempted to chunk up my update by calling a recursive function:
IDBContext context;
try{
context = new MyDbContext();
context.Configuration.AutoDetectChangesEnabled = false;
EncryptFields(context, 500, (count / 500));
}
finally{
if (context != null)
{
context.Dispose();
}
}
Recursive function here:
private static void EncryptFields(IDBContext context, int batchSize, int maxRetries)
{
Debug.WriteLine(maxRetries.ToString());
if (maxRetries == 0)
{
return;
}
var phones = context.Phones
.Where(p => !(p.Number == null
|| p.Number.Trim() == String.Empty))
.Take(batchSize)
.ToList();
if (phones.Count() > 0)
{
foreach (var phone in phones)
{
phone.Enc_Number = Encrypt(phone.Number);
}
context.SaveChanges();
context.Dispose();
context = new MyDBContext();
context.Configuration.AutoDetectChangesEnabled = false;
EncryptFields(context, batchSize, --maxRetries);
}
}
I started off with a maxRetry
value of 1270, but when it dropped to 360, I got a StackOverflow exception on the line:
var phones = context.Phones...
Given I dispose of the context and re-create it after updating every 500 records, I'm unsure why I am getting this exception.