using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using BlueWest.Data; using Microsoft.EntityFrameworkCore; namespace BlueWest.WebApi.EF { /// /// Country table database extensions /// public static class CountryDbExtensions { /// /// Updates a country data. /// /// DbContext. /// Country data to update. /// Country Id. /// public static (bool, Country) UpdateCountry( this CountryDbContext dbContext, CountryUpdate countryUpdate, int countryId) { var country = dbContext.Countries.FirstOrDefault(x => x.Id == countryId); if (country == null) return (false, null); country.Update(countryUpdate); dbContext.Countries.Update(country); var result = dbContext.SaveChanges() >= 0; return (result, country); } /// /// Adds a new Currency to the specified country /// /// /// /// /// public static (bool, string, Country) AddCurrency( this CountryDbContext dbContext, int countryId, CurrencyCreate currencyCreate) { var country = dbContext.Countries.FirstOrDefault(d => d.Id == countryId); // Check if currency exists if (country == null) return (false, "Country Not found.", null); // Creates new currency var newCurrency = new Currency(currencyCreate); country.Currencies.Add(newCurrency); var success = dbContext.SaveChanges() >= 0; return !success ? (false, "Error saving the changes in the database.", null) : (true, string.Empty, country); } /// /// Add Currency with optional duplication checks /// /// /// Country Id /// Data to create currency /// List of expressions /// public static (bool, string, CountryUnique) AddCurrency( this CountryDbContext dbContext, int countryId, CurrencyCreate currencyCreate, Expression>[] duplicationValidations) { var country = dbContext .Countries .Where(data => data.Id == countryId) .Include(o => o.Currencies) .FirstOrDefault(); // Check if currency exists if (country == null) return (false, $"{nameof(country)} Not found.", null); // Check if there's currency with the same code foreach (var duplicationValidation in duplicationValidations) { var currencyToGet = dbContext.Currencies.FirstOrDefault(duplicationValidation); if (currencyToGet != null) { return (false, $"Duplication Validation failed: {nameof(duplicationValidation.Body.ToString)}", null); } } // Creates new currency var newCurrency = new Currency(currencyCreate); country.Currencies.Add(newCurrency); var success = dbContext.SaveChanges() >= 0; return !success ? (false, "Error saving the changes in the database.", null) : (true, string.Empty, new CountryUnique(country)); } } }