/// <summary> /// When the save of a delete or addition operation fails, attempt to retry save the operation by refreshing the local objects before retrying the save. /// </summary> /// <param name="dbModel"></param> private void SaveChangeWithContextReloadUponFailure(SmartEnergyDatabase dbModel) { try { dbModel.SaveChanges(); } catch (DbUpdateException ex) { // Update the values of the entity that failed to save from the store ex.Entries.Single().Reload(); dbModel.SaveChanges(); } }
/// <summary> /// Add a MarketRegion /// </summary> /// <param name="regionName">Region Name</param> /// <param name="currencyName">Currency Name</param> /// <param name="currencyValuePerUSD">Currency Value per US Dollar</param> /// <param name="timeZone">.NET Timezone Name (from the list https://msdn.microsoft.com/en-us/library/ms912391(v=winembedded.11).aspx</param>) /// <param name="latitude">Latitude</param> /// <param name="longitude">Longitude</param> /// <returns>Object representing row created in the database</returns> public MarketRegion AddMarketRegion( string regionName, string currencyName, double currencyValuePerUSD, string timeZone, double?latitude = null, double?longitude = null) { var utcTimeOffset = ConvertTimezoneNameToUtcDateTimeOffset(timeZone); using (var dbObject = new SmartEnergyDatabase(this.DatabaseConnectionString)) { // First check if the region already exists var regionInfoForGivenRegionName = this.FindMarketRegion(regionName); if (regionInfoForGivenRegionName != null) { return(regionInfoForGivenRegionName); } // If it doesn't exist, add it var newRegion = new MarketRegion() { FriendlyName = regionName, CurrencyName = currencyName, CurrencyValuePerUSD = currencyValuePerUSD, TimeZoneUTCRelative = utcTimeOffset, Latitude = latitude, Longitude = longitude }; dbObject.MarketRegions.Add(newRegion); dbObject.SaveChanges(); // Retrieve the new object from the database and return it regionInfoForGivenRegionName = this.FindMarketRegion(regionName); return(regionInfoForGivenRegionName); } }
/// <summary> /// Save changes to the given SmartEnergyDatabase Object Model reference, allowing the calling method to specify the maximum number of retries. If the /// numberOfAttemptsMade exceeds the maxNumberOfRetries allowed, retrying is stopped, and the exception is thrown. /// </summary> /// <param name="maxNumberOfRetries"></param> /// <param name="dbModel"></param> /// <param name="numberOfAttemptsMade"></param> /// <returns></returns> private static bool SaveChangesWithRetry( int maxNumberOfRetries, SmartEnergyDatabase dbModel, ref int numberOfAttemptsMade) { Exception exceptionThrown; try { dbModel.SaveChanges(); return(true); } catch (DataException ex) { numberOfAttemptsMade++; exceptionThrown = ex; } if (numberOfAttemptsMade >= maxNumberOfRetries) { throw exceptionThrown; } return(false); }