protected override void UpdateDatabase(IEntityDb db) { HashSet <string> updated = new HashSet <string>(); var dbCountryLocations = db.CompanyLocations.ToList(); //update existing application codes foreach (var dbCountryLocation in dbCountryLocations) { CompanyLocationModel updateCountries; if (parsedData.TryGetValue(dbCountryLocation.LocationId, out updateCountries)) { dbCountryLocation.CompanyCode = updateCountries.AbacusCode; dbCountryLocation.AddressId = updateCountries.AddressId; dbCountryLocation.LocationType = updateCountries.LocationType; dbCountryLocation.CountryHq = updateCountries.CountryHq; dbCountryLocation.Phone = updateCountries.Phone; dbCountryLocation.Fax = updateCountries.Fax; dbCountryLocation.LocalLanguageName = updateCountries.LocalLanguageName; dbCountryLocation.LocalName = updateCountries.LocalName; dbCountryLocation.MailingAddress = updateCountries.MailingAddress; dbCountryLocation.Comment = updateCountries.Comment; dbCountryLocation.Deleted = updateCountries.IsDeleted; dbCountryLocation.SuccessorId = updateCountries.ReplacedBy; dbCountryLocation.City = updateCountries.City; dbCountryLocation.CompanyName = updateCountries.Name; dbCountryLocation.Street = updateCountries.Street; dbCountryLocation.ZipCode = updateCountries.ZipCode; dbCountryLocation.State = updateCountries.State; updated.Add(dbCountryLocation.LocationId); } else { dbCountryLocation.Deleted = true; } } db.SaveChanges(); //new applications: foreach (var newApplication in parsedData.Where(a => !updated.Contains(a.Value.LocationId))) { db.CompanyLocations.Add(new CompanyLocations() { LocationId = newApplication.Value.LocationId, CompanyCode = newApplication.Value.AbacusCode, AddressId = newApplication.Value.AddressId, LocationType = newApplication.Value.LocationType, CountryHq = newApplication.Value.CountryHq, Phone = newApplication.Value.Phone, Fax = newApplication.Value.Fax, LocalLanguageName = newApplication.Value.LocalLanguageName, LocalName = newApplication.Value.LocalName, MailingAddress = newApplication.Value.MailingAddress, Comment = newApplication.Value.Comment, Deleted = newApplication.Value.IsDeleted, SuccessorId = newApplication.Value.ReplacedBy, City = newApplication.Value.City, CompanyName = newApplication.Value.Name, Street = newApplication.Value.Street, ZipCode = newApplication.Value.ZipCode, State = newApplication.Value.State }); } //update replaceby value: foreach (var updatedRegion in parsedData.Where(a => !string.IsNullOrEmpty(a.Value.ReplacedBy))) { var oldAc = dbCountryLocations.Where(ac => ac.LocationId == updatedRegion.Value.LocationId).FirstOrDefault(); var newAc = dbCountryLocations.Where(ac => ac.LocationId == updatedRegion.Value.ReplacedBy).FirstOrDefault(); oldAc.Deleted = true; oldAc.SuccessorId = newAc.LocationId; //set replaced by } }