public void CheckAssociateContractStatus() { // get associates on contract that have lapsed roles; which have end dates less than today var lapsedRoleAssociates = associateRepo.GetOnContractAssociatesWithElapsedRoles(); // get associates on contract that have current roles; which have end dates less than today dynamic dynamicCurrentRoleAssociates = associateRepo.GetOnContractAssociatesWithCurrentRoles(); var currentRoleAssociates = new List <int>(); foreach (var currentRoleAssociate in dynamicCurrentRoleAssociates) { currentRoleAssociates.Add((int)currentRoleAssociate); } foreach (var lapsedRoleAssociate in lapsedRoleAssociates) { // check if associate has current role var lapsed = true; foreach (var currentRoleAssociate in currentRoleAssociates) { if ((int)lapsedRoleAssociate != (int)currentRoleAssociate) { continue; } lapsed = false; break; } if (!lapsed) { continue; } // get audit chages for AssociateContractStatus List <GetAssociateContractStatusHistory_Result> associateContractStatusList = associateRepo.GetAssociateContractStatusHistory(lapsedRoleAssociate); // update associate to previous contract status var auditRows = (from r in associateContractStatusList where r.AssociateApprovalStatusId != null select r).OrderByDescending(o => o.Sequence).ToList(); if (auditRows.Count == 0) { continue; } int i; for (i = 0; i < auditRows.Count; i++) { if (auditRows[i].AssociateApprovalStatusId == (int)AssociateApprovalStatus.OnContract) { break; } } if (i + 1 < auditRows.Count) { associateRepo.UpdateAssociateContractStatus(lapsedRoleAssociate, auditRows[i + 1].AssociateApprovalStatusId.GetValueOrDefault()); } } }