On the Catch section of a Try-Catch block I need to save a value which is declared in a foreach loop (var crmAccount). I have to declare crmAccount outside the Try to be able to use it in the Catch.
Here is my code:
try
{
lastRunDate = lastRun.LastRunDate;
bool isNew = false;
var crmAccounts = _crmDbContext.AccountSet.Where(a => a.ModifiedOn >= lastRunDate);
foreach (var crmAccount in crmAccounts)
{
var account = dbContext.Accounts.FirstOrDefault(a => a.AccountKey == new Guid(crmAccount.AccountId.ToString()));
if (account == null)
{
account = new Account();
account.AccountKey = new Guid(crmAccount.AccountId.ToString());
isNew = true;
}
else
isNew = false;
account.AccountNumber = crmAccount.AccountNumber;
if (isNew)
dbContext.Accounts.Add(account);
dbContext.SaveChanges();
}
}
catch (Exception ex)
{
IntegrationError intError = new IntegrationError();
intError.Error = ex.ToString();
intError.TableName = "Account";
intError.TableKey = crmAccount.AccountId; // error message because crmAccount is not declared outside the Try block
dbContext.IntegrationErrors.Add(intError);
dbContext.SaveChanges();
How do I declare crmAccount outside the Try so I can use in the Catch without breaking my foreach loop?
Thanks