using System.Linq; using System.Threading.Tasks; using BlueWest.Data; using Microsoft.EntityFrameworkCore; namespace BlueWest.WebApi.EF { internal static class CountryDbExtensions { internal static Country GetCountryById(this DbSet countries, int countryId) => countries.GetOne(x => x.Id == countryId); internal static (bool, T) NotFound() where T : class => (false, null); internal static (bool, Country) AddCountry (this CountryDbContext dbContext, CountryCreate countryCreate) { Country newCountry = new Country(countryCreate); return dbContext.Countries.Add(dbContext, newCountry); } internal static async Task<(bool, Country)> AddCountryAsync (this CountryDbContext dbContext, CountryCreate countryCreate) { var newCountry = new Country(countryCreate); return await dbContext.Countries.AddAsync(dbContext, newCountry); } internal static (bool, Country) UpdateCountry(this CountryDbContext dbContext, CountryUpdate countryUpdate, int countryId) { var country = dbContext.Countries.FirstOrDefault(x => x.Id == countryId); if (country != null) { var updatedCountry = new Country(countryUpdate); return dbContext.Countries.Update(dbContext, updatedCountry); } return NotFound(); } internal static async Task GetCountryByIdAsync(this DbSet countries, int countryId) => await countries.FirstOrDefaultAsync(x => x.Id == countryId); internal static async Task<(bool, Country)> UpdateCountryAsync(this CountryDbContext dbContext, CountryUpdate countryUpdate, int countryCode) { var country = await dbContext.Countries.FirstOrDefaultAsync(x => x.Code == countryCode); if (country != null) { var updatedCountry = new Country(countryUpdate); return await dbContext.Countries.UpdateAsync(dbContext, updatedCountry); } return NotFound(); } } }