//TODO: Update to only update effected Accounts private bool UpdateAccountPaycheckContribution() { try { var updatedAccounts = new List <Account>(); var paycheckContributionsDict = _calc.GetPaycheckContributionsDict(); var accountManager = new AccountManager(); var account = new Account(); // Update paycheck contribution for all accounts foreach (var paycheckContribution in paycheckContributionsDict) { try { account = updatedAccounts.Find(a => string.Equals(a.Name, paycheckContribution.Key, StringComparison.CurrentCultureIgnoreCase)); var accountIndex = -1; if (account == null) { account = new Account { Name = paycheckContribution.Key }; } else { accountIndex = updatedAccounts.FindIndex(a => string.Equals(a.Name, paycheckContribution.Key, StringComparison.CurrentCultureIgnoreCase)); } if (!(paycheckContribution.Value >= account.PaycheckContribution)) { continue; } if (accountIndex >= 0) { updatedAccounts[accountIndex].PaycheckContribution = paycheckContribution.Value; } else { account.PaycheckContribution = paycheckContribution.Value; updatedAccounts.Add(account); } // iterate through all updated accounts and set state to modified to save to database var accounts = accountManager.GetAllAccounts(); foreach (var updatedAccount in updatedAccounts) { try { account = accounts.Find(a => string.Equals(a.Name, updatedAccount.Name, StringComparison.CurrentCultureIgnoreCase)); // shouldn't ever be null since updatedAccounts comes from Accounts in DB account.PaycheckContribution = updatedAccount.PaycheckContribution; account.RequiredSavings = updatedAccount.RequiredSavings; var requiredSurplus = account.Balance - account.RequiredSavings; if (requiredSurplus <= 0) { account.BalanceSurplus = requiredSurplus; } else { if (account.Balance - account.BalanceLimit <= 0) { account.BalanceSurplus = 0; } else { account.BalanceSurplus = account.Balance - account.BalanceLimit; } } _db.Entry(account).State = EntityState.Modified; } catch (Exception e) { Logger.Instance.Error(e); } } // save changes to the database if (_db.ChangeTracker.HasChanges()) { _db.SaveChanges(); } } catch (Exception e) { Logger.Instance.Error(e); } } return(true); } catch (Exception e) { Logger.Instance.Error(e); return(false); } }