using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using BlueWest.Data; using Microsoft.EntityFrameworkCore; namespace BlueWest.WebApi.EF { /// /// Currency table data extensions /// public static class CurrencyExtensions { /// /// Add new Currency /// /// /// /// public static (bool, Currency) AddCurrency(this CountryDbContext dbContext, CurrencyCreate currencyToCreate) { var newCurrency = new Currency(currencyToCreate); dbContext.Add(newCurrency); var resultOperation = dbContext.SaveChanges() >= 0; return (resultOperation, newCurrency); } /// /// Updates currency /// /// /// /// /// public static (bool, Currency) UpdateCurrency(this CountryDbContext dbContext, int currencyId, CurrencyUpdate currencyToUpdate) { var currency = dbContext.Currencies.SingleOrDefault(x => x.Id == currencyId); if (currency == null) return (false, null); currency.Update(currencyToUpdate); dbContext.Update(currency); var resultOperation = dbContext.SaveChanges() >= 0; return (resultOperation, currency); } /// /// Add Country associated with specified Currency. /// /// /// /// /// /// public static (bool, string, CountryUnique) AddCountry( this CountryDbContext dbContext, int currencyId, CountryCreate countryCreate, Expression>[] duplicationValidations) { var queryable = from aCurrency in dbContext.Currencies where aCurrency.Id == currencyId select aCurrency; queryable.Include(x => x.Countries); var currency = queryable.SingleOrDefault(); // Check if currency exists if (currency == null) return (false, $"{nameof(Currency)}: {currencyId} - Not found.", null); // Check if there's currency with the same code foreach (var duplicationValidation in duplicationValidations) { var countryToCheck = dbContext.Countries.FirstOrDefault(duplicationValidation); if (countryToCheck != null) { return (false, $"Duplication Validation failed: {duplicationValidation.Body}", null); } } // Creates new currency var newCountry = new Country(countryCreate); currency.Countries.Add(newCountry); var success = dbContext.SaveChanges() >= 0; return (success, string.Empty, new CountryUnique(newCountry)); } } }