Quantcast
Channel: CRM Development forum
Viewing all articles
Browse latest Browse all 8223

I need help with variable scope for XRM C# code

$
0
0

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


Viewing all articles
Browse latest Browse all 8223

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>