public IHttpActionResult SaveFrayteZoneCountry(FrayteZoneCountry zonecountry) { new ZoneCountryRepository().AddCountryZone(zonecountry); return(Ok()); }
public void AddCountryZone(FrayteZoneCountry zone) { try { if (zone != null) { //Step 1: Get the list of all the countries related to the zone from db. var list = (from zoneCount in dbContext.LogisticServiceZoneCountries where zoneCount.LogisticServiceZoneId == zone.ZoneId select zoneCount).ToList(); //Step 2: Remove Countries, for this need to find the country which is in db list but not in UI list var result = list.Where(p => !zone.Fraytezonezountry.Any(p2 => p2.CountryId == p.CountryId)).ToList(); foreach (var removeObj in result) { LogisticServiceZoneCountry removeData = dbContext.LogisticServiceZoneCountries.Where(p => p.CountryId == removeObj.CountryId && p.LogisticServiceZoneId == removeObj.LogisticServiceZoneId).FirstOrDefault(); if (removeData != null) { dbContext.LogisticServiceZoneCountries.Remove(removeData); dbContext.SaveChanges(); } } //Step 3: Add Countries, for this need to find the countries which is in UI list but not in db list var result1 = zone.Fraytezonezountry.Where(p => !list.Any(p2 => p2.CountryId == p.CountryId)).ToList(); foreach (var addObj in result1) { LogisticServiceZoneCountry newZoneCountry = new LogisticServiceZoneCountry(); newZoneCountry.LogisticServiceZoneId = zone.ZoneId; newZoneCountry.CountryId = addObj.CountryId; newZoneCountry.OperationZoneId = zone.OperationZoneId; newZoneCountry.TransitTime = addObj.TransitTime; dbContext.LogisticServiceZoneCountries.Add(newZoneCountry); dbContext.SaveChanges(); } //Step 4: Update Transit Time For Zone Country var transitlist = (from zoneCount in dbContext.LogisticServiceZoneCountries where zoneCount.LogisticServiceZoneId == zone.ZoneId select zoneCount).ToList(); if (transitlist.Count > 0) { int j = 0; foreach (var ll in transitlist) { if (ll.LogisticZoneCountryId > 0) { var transit = dbContext.LogisticServiceZoneCountries.Where(p => p.LogisticZoneCountryId == ll.LogisticZoneCountryId).FirstOrDefault(); if (transit != null) { transit.LogisticZoneCountryId = ll.LogisticZoneCountryId; transit.TransitTime = zone.Fraytezonezountry[j].TransitTime; dbContext.Entry(transit).State = System.Data.Entity.EntityState.Modified; dbContext.SaveChanges(); } j++; } } } } } catch (DbEntityValidationException ex) { foreach (var entityValidationErrors in ex.EntityValidationErrors) { foreach (var validationError in entityValidationErrors.ValidationErrors) { string ss = "Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage; } } } }