From 924865066df7596ff9d0ce85ecc4cccabf9af140 Mon Sep 17 00:00:00 2001 From: CodeLiturgy Date: Thu, 8 Sep 2022 04:15:44 +0100 Subject: [PATCH] AddToList Template --- BlueWest.Api/BlueWest.Api.csproj | 7 ++- BlueWest.Api/Context/CountryDbContext.cs | 45 ++++---------- .../ModelBuilderCountryDbContextExtensions.cs | 59 +++++++++++++++++++ .../Extensions/ModelBuilderExtensions.cs | 4 -- BlueWest.Api/Context/FinanceDbContext.cs | 16 ++++- .../Context/Templates/AddToListTemplate.csx | 32 +++++----- ...ToEntityTemplate.csx => AddToTemplate.csx} | 1 - .../Context/Templates/GetListTemplate.csx | 34 +++++++++++ .../Context/Templates/GetOneByTemplate.csx | 1 - .../Context/Templates/GetOneTemplate.csx | 4 +- ...eEntityTemplate.csx => UpdateTemplate.csx} | 0 BlueWest.Api/Controllers/CountryController.cs | 56 ++++++++++++++---- .../ModelBuilderMigrationExtensions.cs | 34 ----------- .../{Extensions => }/StartupExtensions.cs | 10 ++-- BlueWest.Frontend | 2 +- include/BlueWest.EfMethods | 2 +- 16 files changed, 195 insertions(+), 112 deletions(-) create mode 100644 BlueWest.Api/Context/Extensions/ModelBuilderCountryDbContextExtensions.cs rename BlueWest.Api/{ => Context}/Extensions/ModelBuilderExtensions.cs (98%) rename BlueWest.Api/Context/Templates/{AddToEntityTemplate.csx => AddToTemplate.csx} (99%) create mode 100644 BlueWest.Api/Context/Templates/GetListTemplate.csx rename BlueWest.Api/Context/Templates/{UpdateEntityTemplate.csx => UpdateTemplate.csx} (100%) delete mode 100644 BlueWest.Api/Extensions/ModelBuilderMigrationExtensions.cs rename BlueWest.Api/{Extensions => }/StartupExtensions.cs (94%) diff --git a/BlueWest.Api/BlueWest.Api.csproj b/BlueWest.Api/BlueWest.Api.csproj index ca67f72..d911de2 100644 --- a/BlueWest.Api/BlueWest.Api.csproj +++ b/BlueWest.Api/BlueWest.Api.csproj @@ -34,12 +34,13 @@ - - + + - + + diff --git a/BlueWest.Api/Context/CountryDbContext.cs b/BlueWest.Api/Context/CountryDbContext.cs index 9eb4a8b..fc2c7ac 100644 --- a/BlueWest.Api/Context/CountryDbContext.cs +++ b/BlueWest.Api/Context/CountryDbContext.cs @@ -1,7 +1,7 @@ using BlueWest.Data; using BlueWest.WebApi.EF.Model; using BlueWest.EfMethods; -using BlueWest.WebApi.Extensions; +using BlueWest.WebApi.Context.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; @@ -16,29 +16,19 @@ namespace BlueWest.WebApi.EF { #region Countries + /// - /// Countries Database Table + /// Countries /// - [EfGetOneBy( - nameof(Country.Id), - typeof(CountryUnique))] - + [EfGetOneBy(nameof(Country.Id), typeof(CountryUnique))] [EfGetOne(typeof(CountryUnique))] - - [EfAddMethods( - createType: typeof(CountryCreate), - returnType: typeof(CountryUnique)) - ] - [EfUpdateMethods( - updateType: typeof(CountryUpdate), - returnType: typeof(CountryUnique), - keyPropertyMemberName: nameof(Country.Id)) - ] - + [EfAddMethods(createType: typeof(CountryCreate), returnType: typeof(CountryUnique))] + [EfUpdateMethods( updateType: typeof(CountryUpdate), returnType: typeof(CountryUnique), keyPropertyMemberName: nameof(Country.Id))] [EfGetMany(typeof(CountryUnique))] - - + [EfAddToList(nameof(Country.Currencies), typeof(CurrencyCreate), typeof(CurrencyUnique), nameof(Country.Id))] + [EfGetList(nameof(Country.Currencies), typeof(CurrencyUnique), nameof(Country.Id))] + public DbSet Countries { get; set; } #endregion @@ -50,20 +40,11 @@ namespace BlueWest.WebApi.EF /// [EfAddMethods(typeof(CurrencyCreate), typeof(CurrencyUnique))] - - [EfUpdateMethods( - updateType: typeof(CurrencyUpdate), - returnType: typeof(CurrencyUnique), - keyPropertyMemberName: nameof(Currency.Id)) + [EfUpdateMethods( updateType: typeof(CurrencyUpdate), returnType: typeof(CurrencyUnique), keyPropertyMemberName: nameof(Currency.Id))] + [EfGetOneBy(nameof(Currency.Id), typeof(CurrencyUnique))] + [EfGetOne(typeof(CurrencyUnique))] + [EfGetList(nameof(Currency.Countries), typeof(CountryUnique), nameof(Currency.Id)) ] - - [EfGetOneBy( - nameof(Currency.Id), - typeof(CurrencyUnique))] - - [EfGetOne( - typeof(CurrencyUnique))] - public DbSet Currencies { get; set; } #endregion diff --git a/BlueWest.Api/Context/Extensions/ModelBuilderCountryDbContextExtensions.cs b/BlueWest.Api/Context/Extensions/ModelBuilderCountryDbContextExtensions.cs new file mode 100644 index 0000000..87ac2d3 --- /dev/null +++ b/BlueWest.Api/Context/Extensions/ModelBuilderCountryDbContextExtensions.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using BlueWest.Data; +using Microsoft.EntityFrameworkCore; + +namespace BlueWest.WebApi.Context.Extensions +{ + public static class ModelBuilderCountryDbContextExtensions + { /// + /// Setup the database model + /// + /// + public static void AddCurrencyAndCountryData(this ModelBuilder modelBuilder) + { + + + var currencies = new List(); + + var usaCountry = new Country(); + + usaCountry.Id = 1; + usaCountry.Code = 1; + usaCountry.Name = "United States"; + usaCountry.Alpha2Code = "US"; + usaCountry.StateName = "United States of America"; + usaCountry.TLD = "us"; + + var germanyCountry = new Country(); + + germanyCountry.Id = 2; + germanyCountry.Code = 2; + germanyCountry.Name = "Germany"; + germanyCountry.Alpha2Code = "DE"; + germanyCountry.StateName = "Germany"; + germanyCountry.TLD = "de"; + + var dolar = new Currency(); + dolar.Id = 1; + dolar.Code = "USD"; + dolar.Countries = new List(); + dolar.Countries.Add(usaCountry); + dolar.Num = 1; + + + var euro = new Currency(); + euro.Id = 2; + euro.Code = "EUR"; + euro.Countries = new List(); + euro.Countries.Add(germanyCountry); + euro.Num = 2; + + + modelBuilder + .Entity() + .HasData(currencies.ToArray()); + } + + } +} + diff --git a/BlueWest.Api/Extensions/ModelBuilderExtensions.cs b/BlueWest.Api/Context/Extensions/ModelBuilderExtensions.cs similarity index 98% rename from BlueWest.Api/Extensions/ModelBuilderExtensions.cs rename to BlueWest.Api/Context/Extensions/ModelBuilderExtensions.cs index a462855..4f1aa0d 100644 --- a/BlueWest.Api/Extensions/ModelBuilderExtensions.cs +++ b/BlueWest.Api/Context/Extensions/ModelBuilderExtensions.cs @@ -123,10 +123,6 @@ namespace BlueWest.WebApi.EF.Model #endregion - #region Migrations - - - #endregion } } diff --git a/BlueWest.Api/Context/FinanceDbContext.cs b/BlueWest.Api/Context/FinanceDbContext.cs index b6fbf8d..dcf742e 100644 --- a/BlueWest.Api/Context/FinanceDbContext.cs +++ b/BlueWest.Api/Context/FinanceDbContext.cs @@ -9,15 +9,26 @@ namespace BlueWest.WebApi.EF /// public sealed class FinanceDbContext : DbContext { + #region Transactions + /// /// Table storing transactions /// public DbSet Transactions { get; set; } - + + #endregion + + #region TransactionType + /// /// Table storing transaction types. /// public DbSet TransactionTypes { get; set; } + + + #endregion + + #region Initialization /// /// CompanyDbContext constructor. @@ -37,6 +48,9 @@ namespace BlueWest.WebApi.EF base.OnModelCreating(modelBuilder); modelBuilder.ConfigureCurrentDbModel(); } + + #endregion + } } diff --git a/BlueWest.Api/Context/Templates/AddToListTemplate.csx b/BlueWest.Api/Context/Templates/AddToListTemplate.csx index 6d294f0..58a1797 100644 --- a/BlueWest.Api/Context/Templates/AddToListTemplate.csx +++ b/BlueWest.Api/Context/Templates/AddToListTemplate.csx @@ -1,26 +1,26 @@ -public static (bool, string, {returnTypeFullName}) Add{listEntityTypeName}To{entityTypeName}( this {contextFullName} dbContext, - {keyTypeFullName} {keyVarName}, {listEntityCreateFullName} {listItemCreateVarName}, Expression>[] duplicationValidations) +/// +/// Adds a new item into {listPropertyName} from {entityTypeName}. +/// +/// The database context. +/// The {entityTypeName} key to get +/// The item to add to {listPropertyName}. +/// The success of the operation, a message, and a projection of the added item. +public static (bool, string, {returnTypeFullName}) Add{listEntityTypeName}To{entityTypeName}(this {contextFullName} dbContext, + {primaryKeyFullName} {primaryKeyVarName}, {listEntityCreateFullName} {listItemCreateVarName}) { var entityQuery = from aEntity in dbContext.{propertyName} - where aEntity.{keyVarName} == {keyVarName} - let itemsInList = aEntity.{entityListMemberName} + where aEntity.{primaryKeyPropertyName} == {primaryKeyVarName} + let itemsInList = aEntity.{listPropertyName} select aEntity; var entity = entityQuery.FirstOrDefault(); - if (entity == null) return (false, $"{nameof(country)} Not found.", null); - - foreach (var duplicationValidation in duplicationValidations) - { - var entityToGet = dbContext.{entityListMemberName}.FirstOrDefault(duplicationValidation); - if (entityToGet != null) - { - return (false, $"Duplication Validation failed: {nameof(duplicationValidation.Body.ToString)}", null); - } - } + if (entity == null) return (false, $"{entityTypeName} Not found.", null); var newListItem = new {listEntityFullName}({listItemCreateVarName}); - entity.{entityListMemberName}.Add({listItemCreateVarName}); + entity.{listPropertyName}.Add(newListItem); var success = dbContext.SaveChanges() >= 0; - return !success ? (false, "Error saving changes.", null) : (true, string.Empty, new {returnTypeFullName}(newListItem)); + + return !success ? (false, "Error saving changes in the Database. Action: Create {listEntityTypeName} in {entityTypeName}.", null) : + (true, string.Empty, new {returnTypeFullName}(newListItem)); } \ No newline at end of file diff --git a/BlueWest.Api/Context/Templates/AddToEntityTemplate.csx b/BlueWest.Api/Context/Templates/AddToTemplate.csx similarity index 99% rename from BlueWest.Api/Context/Templates/AddToEntityTemplate.csx rename to BlueWest.Api/Context/Templates/AddToTemplate.csx index ef7744b..1ab2465 100644 --- a/BlueWest.Api/Context/Templates/AddToEntityTemplate.csx +++ b/BlueWest.Api/Context/Templates/AddToTemplate.csx @@ -4,7 +4,6 @@ /// The database context. /// Projection data of {entityTypeName} /// The added data. - public static (bool, {returnTypeFullName}) Add{entityTypeName}(this {contextFullName} dbContext, {createTypeFullName} {toCreateVarName}) { var {newEntityVarName} = new {entityTypeFullName}({toCreateVarName}); diff --git a/BlueWest.Api/Context/Templates/GetListTemplate.csx b/BlueWest.Api/Context/Templates/GetListTemplate.csx new file mode 100644 index 0000000..32d5451 --- /dev/null +++ b/BlueWest.Api/Context/Templates/GetListTemplate.csx @@ -0,0 +1,34 @@ +/// +/// Gets {listPropertyName} in {entityTypeName}. +/// +/// The database context. +/// The {entityTypeName} key to get +/// How many {propertyName} to skip. +/// How many {propertyName} to take. (Default = 50) +/// Optional Order direction +/// Optional where predicate. +/// Optional order by predicate. +/// A bool if there's at least one record found and the resulting array. +public static (bool, {returnTypeFullName}[]) Get{entityTypeName}{listPropertyName}(this {contextFullName} dbContext, {primaryKeyFullName} {primaryKeyVarName}, + int skip = 0, int take = 50, int orderDir = 1, + Expression> orderBy = null) +{ + var {entityObjectVarName} = dbContext.{propertyName}.FirstOrDefault(d => d.{primaryKeyPropertyName} == {primaryKeyVarName}); + + if ({entityObjectVarName} == null) return (false, null); + + var currentTake = take; + if (take > 200) currentTake = 200; + + var query = dbContext + .{propertyName} + .Where(data => data.{primaryKeyPropertyName} == {primaryKeyVarName}) + .SelectMany(o => o.{listPropertyName}) + .Select(x => new {returnTypeFullName}(x)) + .Skip(skip) + .Take(currentTake); + + if(orderBy != null) query = orderDir == 1 ? query.OrderBy(orderBy) : query.OrderByDescending(orderBy); + + return (query.Any(), query.ToArray()); +} \ No newline at end of file diff --git a/BlueWest.Api/Context/Templates/GetOneByTemplate.csx b/BlueWest.Api/Context/Templates/GetOneByTemplate.csx index 6f72f4c..af1473e 100644 --- a/BlueWest.Api/Context/Templates/GetOneByTemplate.csx +++ b/BlueWest.Api/Context/Templates/GetOneByTemplate.csx @@ -4,7 +4,6 @@ /// The database context. /// By {byParamPropertyName} parameter type. /// A bool if the result is successfull, and the first occurrence of {entityTypeName}> - public static (bool, {returnTypeFullName}) GetOne{entityTypeName}By{byParamPropertyName} (this {contextFullName} dbContext, {byParamFullType} {byParamVarName}) { var {findEntityVarName} = dbContext.{propertyName} diff --git a/BlueWest.Api/Context/Templates/GetOneTemplate.csx b/BlueWest.Api/Context/Templates/GetOneTemplate.csx index 0462426..0436400 100644 --- a/BlueWest.Api/Context/Templates/GetOneTemplate.csx +++ b/BlueWest.Api/Context/Templates/GetOneTemplate.csx @@ -4,8 +4,8 @@ /// The database context. /// FirstOrDefault argument to pass. /// A bool if the first occurrence of {returnTypeName} is returned. - -public static (bool, {returnTypeFullName}) Get{entityTypeName}With (this {contextFullName} dbContext, Expression> with) +public static (bool, {returnTypeFullName}) Get{entityTypeName}With (this {contextFullName} dbContext, + Expression> with) { var {findEntityVarName} = dbContext.{propertyName} diff --git a/BlueWest.Api/Context/Templates/UpdateEntityTemplate.csx b/BlueWest.Api/Context/Templates/UpdateTemplate.csx similarity index 100% rename from BlueWest.Api/Context/Templates/UpdateEntityTemplate.csx rename to BlueWest.Api/Context/Templates/UpdateTemplate.csx diff --git a/BlueWest.Api/Controllers/CountryController.cs b/BlueWest.Api/Controllers/CountryController.cs index adc668b..8e84f39 100644 --- a/BlueWest.Api/Controllers/CountryController.cs +++ b/BlueWest.Api/Controllers/CountryController.cs @@ -32,6 +32,8 @@ namespace BlueWest.WebApi.Controllers #endregion + #region GetCountries + /// /// Get countries /// @@ -44,13 +46,18 @@ namespace BlueWest.WebApi.Controllers int take = 50, int orderDir = 1) { + var (success, countries) = _dbContext.GetCountries(skip, take); if (!success) return new NotFoundResult(); return Ok(countries); } - + #endregion + + + #region GetCountryById + /// /// Get Country by Id /// @@ -71,6 +78,9 @@ namespace BlueWest.WebApi.Controllers return new NotFoundResult(); } + #endregion + + /// /// Get currencies of a countryId @@ -80,23 +90,34 @@ namespace BlueWest.WebApi.Controllers [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [HttpGet("{countryId}/currencies")] - public ActionResult GetCountryCurrencies(int countryId) + public ActionResult GetCountryCurrencies(int countryId, int skip = 0, int take = 50, int orderDir = 1, Expression> orderBy = null) { var countryObj = _dbContext.Countries.FirstOrDefault(d => d.Id == countryId); if (countryObj == null) return new NotFoundResult(); - var array = _dbContext + var currentTake = take; + if (take > 200) currentTake = 200; + + var query = _dbContext .Countries .Where(data => data.Id == countryId) .SelectMany(o => o.Currencies) .Select(x => new CurrencyUnique(x)) - .ToArray(); + .Skip(skip) + .Take(currentTake); + + if(orderBy != null) + { + if (orderDir == 1) query = query.OrderBy(orderBy); + else query = query.OrderByDescending(orderBy); + } - return Ok(array); + return Ok(query.ToArray()); } - + #region AddCountry + /// /// Add Country /// @@ -128,6 +149,11 @@ namespace BlueWest.WebApi.Controllers return CreatedAtRoute(nameof(GetCountryById), new {countryId = country.Id}, country); } + + #endregion + + #region UpdateCountry + /// /// Updates a Country /// @@ -149,6 +175,9 @@ namespace BlueWest.WebApi.Controllers return new NotFoundResult(); } + #endregion + + #region AddCurrencyToCountry /// /// Adds a currency to Country @@ -159,14 +188,14 @@ namespace BlueWest.WebApi.Controllers [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status409Conflict)] [HttpPost("{countryId}/currencies")] - public ActionResult AddCurrency(int countryId, CurrencyCreate currencyCreate) + public ActionResult AddCurrencyToCountry(int countryId, CurrencyCreate currencyCreate) { /*var (result, message, country) = _dbContext.AddCurrency(countryId, currencyCreate, new Expression>[] - { - x => x.Code == currencyCreate.Code, - y => y.Num == currencyCreate.Num - }); + { + x => x.Code == currencyCreate.Code, + y => y.Num == currencyCreate.Num + }); if (!result) { @@ -174,8 +203,11 @@ namespace BlueWest.WebApi.Controllers } return Ok(country);*/ - return null; + throw new NotImplementedException(); } + + #endregion + } diff --git a/BlueWest.Api/Extensions/ModelBuilderMigrationExtensions.cs b/BlueWest.Api/Extensions/ModelBuilderMigrationExtensions.cs deleted file mode 100644 index bb6a984..0000000 --- a/BlueWest.Api/Extensions/ModelBuilderMigrationExtensions.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Collections.Generic; -using BlueWest.Data; -using BlueWest.WebApi.EF.Model; -using Microsoft.EntityFrameworkCore; - -namespace BlueWest.WebApi.Extensions -{ - public static class ModelBuilderMigrationExtensions - { - /// - /// Setup the database model - /// - /// - public static void AddCurrencyAndCountryData(this ModelBuilder modelBuilder) - { - - var countriesToAdd = new List(); - var country = new Country(); - - country.Id = 1; - country.Code = 1; - country.Name = "United States"; - country.Alpha2Code = "US"; - country.StateName = "United States of America"; - countriesToAdd.Add(country); - - modelBuilder - .Entity() - .HasData(countriesToAdd.ToArray()); - } - - } -} - diff --git a/BlueWest.Api/Extensions/StartupExtensions.cs b/BlueWest.Api/StartupExtensions.cs similarity index 94% rename from BlueWest.Api/Extensions/StartupExtensions.cs rename to BlueWest.Api/StartupExtensions.cs index 58f9540..65b43b7 100644 --- a/BlueWest.Api/Extensions/StartupExtensions.cs +++ b/BlueWest.Api/StartupExtensions.cs @@ -80,11 +80,13 @@ namespace BlueWest.WebApi public static IServiceCollection PrepareSqlLiteDatabasePool(this IServiceCollection serviceCollection, IConfiguration configuration, IWebHostEnvironment environment) { + var sqliteConString = "Data Source=BlueWest.Api.db"; + return serviceCollection - .AddDbContextPool(options => options.UseSqlite("Data Source=BlueWest.Api.db")) - .AddDbContextPool(options => options.UseSqlite("Data Source=BlueWest.Api.db")) - .AddDbContextPool(options => options.UseSqlite("Data Source=BlueWest.Api.db")) - .AddDbContextPool(options => options.UseSqlite("Data Source=BlueWest.Api.db")); + .AddDbContextPool(options => options.UseSqlite(sqliteConString)) + .AddDbContextPool(options => options.UseSqlite(sqliteConString)) + .AddDbContextPool(options => options.UseSqlite(sqliteConString)) + .AddDbContextPool(options => options.UseSqlite(sqliteConString)); } } diff --git a/BlueWest.Frontend b/BlueWest.Frontend index ba851c4..e85e5d1 160000 --- a/BlueWest.Frontend +++ b/BlueWest.Frontend @@ -1 +1 @@ -Subproject commit ba851c4f946fd370f888a8aa902ac5f46a982e73 +Subproject commit e85e5d18a2df4957905fda02e216850385bb29da diff --git a/include/BlueWest.EfMethods b/include/BlueWest.EfMethods index 33fbb36..dc23c79 160000 --- a/include/BlueWest.EfMethods +++ b/include/BlueWest.EfMethods @@ -1 +1 @@ -Subproject commit 33fbb36fb85cabaa8995ac8e16e5ed6fdd733805 +Subproject commit dc23c797975f1e4d835b5e67a5c0972813567ce1