From 51daeef315fa83852ada5c25849428c3350cbd53 Mon Sep 17 00:00:00 2001 From: Dimitar Georgiev Dimitrov Date: Fri, 20 Sep 2024 13:46:07 +0300 Subject: [PATCH 1/5] initial --- NorthwindCRUD.Tests/CustomerServiceFixture.cs | 40 +- NorthwindCRUD.Tests/Helpers/DataHelper.cs | 9 +- NorthwindCRUD/Controllers/BaseController.cs | 135 +++++ .../Controllers/CategoriesController.cs | 501 +++++++++--------- .../Controllers/CustomersController.cs | 213 +------- NorthwindCRUD/Controllers/OrdersController.cs | 2 +- .../ControllersGraphQL/CustomerController.cs | 36 +- NorthwindCRUD/Models/DbModels/AddressDb.cs | 2 +- NorthwindCRUD/Models/DbModels/CategoryDb.cs | 2 +- NorthwindCRUD/Models/DbModels/CustomerDb.cs | 7 +- NorthwindCRUD/Models/DbModels/EmployeeDb.cs | 2 +- .../Models/DbModels/EmployeeTerritoryDb.cs | 2 +- NorthwindCRUD/Models/DbModels/IBaseDb.cs | 10 + NorthwindCRUD/Models/DbModels/OrderDb.cs | 5 +- .../Models/DbModels/OrderDetailDb.cs | 2 +- NorthwindCRUD/Models/DbModels/ProductDb.cs | 2 +- NorthwindCRUD/Models/DbModels/RegionDb.cs | 2 +- NorthwindCRUD/Models/DbModels/ShipperDb.cs | 2 +- NorthwindCRUD/Models/DbModels/SupplierDb.cs | 2 +- NorthwindCRUD/Models/DbModels/TerritoryDb.cs | 2 +- NorthwindCRUD/Models/DbModels/UserDb.cs | 2 +- NorthwindCRUD/Models/Dtos/AddressDto.cs | 2 +- .../Models/Dtos/CategoryDetailsDto.cs | 2 +- NorthwindCRUD/Models/Dtos/CategoryDto.cs | 2 +- NorthwindCRUD/Models/Dtos/CountResultDto.cs | 2 +- NorthwindCRUD/Models/Dtos/CustomerDto.cs | 2 +- NorthwindCRUD/Models/Dtos/EmployeeDto.cs | 2 +- .../Models/Dtos/EmployeeTerritoryDto.cs | 2 +- NorthwindCRUD/Models/Dtos/IBaseDto.cs | 6 + NorthwindCRUD/Models/Dtos/LoginDto.cs | 2 +- NorthwindCRUD/Models/Dtos/OrderDetailDto.cs | 2 +- NorthwindCRUD/Models/Dtos/OrderDto.cs | 2 +- NorthwindCRUD/Models/Dtos/ProductDto.cs | 2 +- NorthwindCRUD/Models/Dtos/RegionDto.cs | 2 +- NorthwindCRUD/Models/Dtos/RegisterDto.cs | 2 +- NorthwindCRUD/Models/Dtos/SalesDto.cs | 2 +- NorthwindCRUD/Models/Dtos/ShipperDto.cs | 2 +- NorthwindCRUD/Models/Dtos/SupplierDto.cs | 2 +- NorthwindCRUD/Models/Dtos/TerritoryDto.cs | 2 +- NorthwindCRUD/Program.cs | 2 +- NorthwindCRUD/Services/BaseDbService.cs | 148 ++++++ NorthwindCRUD/Services/CategoryService.cs | 51 +- NorthwindCRUD/Services/CustomerService.cs | 112 +--- NorthwindCRUD/Services/OrderService.cs | 12 +- 44 files changed, 643 insertions(+), 702 deletions(-) create mode 100644 NorthwindCRUD/Controllers/BaseController.cs create mode 100644 NorthwindCRUD/Models/DbModels/IBaseDb.cs create mode 100644 NorthwindCRUD/Models/Dtos/IBaseDto.cs create mode 100644 NorthwindCRUD/Services/BaseDbService.cs diff --git a/NorthwindCRUD.Tests/CustomerServiceFixture.cs b/NorthwindCRUD.Tests/CustomerServiceFixture.cs index 83ede50..6a85951 100644 --- a/NorthwindCRUD.Tests/CustomerServiceFixture.cs +++ b/NorthwindCRUD.Tests/CustomerServiceFixture.cs @@ -8,34 +8,34 @@ public class CustomerServiceFixture : BaseFixture [TestMethod] public void ShouldCreateCustomer() { - var customer = DataHelper.GetCustomer(); - var createdCustomer = DataHelper.CustomerService.Create(customer); - Assert.IsNotNull(createdCustomer); - Assert.AreEqual(customer, createdCustomer, "Customers instances should be the same since we are over the same context"); + //var customer = DataHelper.GetCustomer(); + //var createdCustomer = DataHelper.CustomerService.Create(customer); + //Assert.IsNotNull(createdCustomer); + //Assert.AreEqual(customer, createdCustomer, "Customers instances should be the same since we are over the same context"); - createdCustomer = DataHelper2.CustomerService.GetById(createdCustomer.CustomerId); - Assert.IsNotNull(createdCustomer); - Assert.AreNotEqual(customer, createdCustomer, "Customer instances should be different"); + ////createdCustomer = DataHelper2.CustomerService.GetById(createdCustomer.CustomerId); + //Assert.IsNotNull(createdCustomer); + //Assert.AreNotEqual(customer, createdCustomer, "Customer instances should be different"); - Assert.AreEqual(customer.CompanyName, createdCustomer.CompanyName); - Assert.AreEqual(customer.ContactName, createdCustomer.ContactName); - Assert.AreEqual(customer.ContactTitle, createdCustomer.ContactTitle); - Assert.AreEqual(customer.Address.Street, createdCustomer.Address.Street); - Assert.AreEqual(customer.Address.City, createdCustomer.Address.City); - Assert.AreEqual(customer.Address.PostalCode, createdCustomer.Address.PostalCode); - Assert.AreEqual(customer.Address.Country, createdCustomer.Address.Country); - Assert.AreEqual(customer.Address.Phone, createdCustomer.Address.Phone); + //Assert.AreEqual(customer.CompanyName, createdCustomer.CompanyName); + //Assert.AreEqual(customer.ContactName, createdCustomer.ContactName); + //Assert.AreEqual(customer.ContactTitle, createdCustomer.ContactTitle); + //Assert.AreEqual(customer.Address.Street, createdCustomer.Address.Street); + //Assert.AreEqual(customer.Address.City, createdCustomer.Address.City); + //Assert.AreEqual(customer.Address.PostalCode, createdCustomer.Address.PostalCode); + //Assert.AreEqual(customer.Address.Country, createdCustomer.Address.Country); + //Assert.AreEqual(customer.Address.Phone, createdCustomer.Address.Phone); } [TestMethod] public void ShouldReturnAllCustomers() { - DataHelper.CustomerService.Create(DataHelper.GetCustomer()); - DataHelper.CustomerService.Create(DataHelper.GetCustomer()); + //DataHelper.CustomerService.Create(DataHelper.GetCustomer()); + //DataHelper.CustomerService.Create(DataHelper.GetCustomer()); - var result = DataHelper2.CustomerService.GetAll(); - Assert.IsNotNull(result); - Assert.AreEqual(2, result.Length); + //var result = DataHelper2.CustomerService.GetAll(); + //Assert.IsNotNull(result); + //Assert.AreEqual(2, result.Length); } } } \ No newline at end of file diff --git a/NorthwindCRUD.Tests/Helpers/DataHelper.cs b/NorthwindCRUD.Tests/Helpers/DataHelper.cs index d6d6852..202a8a3 100644 --- a/NorthwindCRUD.Tests/Helpers/DataHelper.cs +++ b/NorthwindCRUD.Tests/Helpers/DataHelper.cs @@ -13,14 +13,14 @@ public class DataHelper public DataHelper(DataContext dataContext) { this.dataContext = dataContext; - CategoryService = new CategoryService(dataContext); - CustomerService = new CustomerService(dataContext); + //CategoryService = new CategoryService(dataContext); + //CustomerService = new CustomerService(dataContext); EmployeeService = new EmployeeService(dataContext); ProductService = new ProductService(dataContext); SupplierService = new SupplierService(dataContext); RegionService = new RegionService(dataContext); TerritoryService = new TerritoryService(dataContext); - OrderService = new OrderService(dataContext); + //OrderService = new OrderService(dataContext); ShipperService = new ShipperService(dataContext); EmployeeTerritoryService = new EmployeeTerritoryService(dataContext); SalesService = new SalesService(dataContext); @@ -115,7 +115,8 @@ internal RegionDb CreateRegion() internal CustomerDb CreateCustomer() { - return CustomerService.Create(GetCustomer()); + return null; + //return CustomerService.Create(GetCustomer()); } internal OrderDb CreateOrder(string? orderDate = null, string? country = null, ProductDb? product = null, int? quantity = null) diff --git a/NorthwindCRUD/Controllers/BaseController.cs b/NorthwindCRUD/Controllers/BaseController.cs new file mode 100644 index 0000000..10e6ca3 --- /dev/null +++ b/NorthwindCRUD/Controllers/BaseController.cs @@ -0,0 +1,135 @@ +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; +using NorthwindCRUD.Services; + +namespace NorthwindCRUD.Controllers +{ + public class BaseController : ControllerBase + where TDto : class, IBaseDto + where TDb : class, IBaseDb, new() + { + private readonly BaseDbService baseDbService; + private readonly ILogger logger; + + public BaseController(BaseDbService baseDbService, ILogger logger) + { + this.baseDbService = baseDbService; + this.logger = logger; + } + + [HttpGet] + public ActionResult GetAll() + { + try + { + var result = this.baseDbService.GetAll(); + return Ok(result); + } + catch (Exception error) + { + logger.LogError(error.Message); + return StatusCode(500); + } + } + + /// + /// Fetches all customers or a page of customers based on the provided parameters. + /// + /// The number of records to skip before starting to fetch the customers. If this parameter is not provided, fetching starts from the beginning. + /// The maximum number of customers to fetch. If this parameter is not provided, all customers are fetched. + /// A comma-separated list of fields to order the customers by, along with the sort direction (e.g., "field1 asc, field2 desc"). + /// A PagedResultDto object containing the fetched T and the total record count. + [HttpGet("GetWithSkip")] + public ActionResult> GetWithSkip( + [FromQuery][Attributes.SwaggerSkipParameter][Range(1, int.MaxValue, ErrorMessage = "Skip must be greater than 0.")] int? skip, + [FromQuery][Attributes.SwaggerTopParameter] int? top, + [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) + { + try + { + var pagedResult = this.baseDbService.GetWithPageSkip(skip, top, null, null, orderBy); + + return Ok(pagedResult); + } + catch (Exception error) + { + logger.LogError(error.Message); + return StatusCode(500); + } + } + + /// + /// Fetches all customers or a page of customers based on the provided parameters. + /// + /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). + /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. + /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). + /// A PagedResultDto object containing the fetched T and the total record count. + [HttpGet("GetWithPage")] + public ActionResult> GetWithPage( + [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, + [FromQuery][Attributes.SwaggerSizeParameter] int? size, + [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) + { + try + { + var pagedResult = this.baseDbService.GetWithPageSkip(null, null, pageIndex, size, orderBy); + + return Ok(pagedResult); + } + catch (Exception error) + { + logger.LogError(error.Message); + return StatusCode(500); + } + } + + [HttpPost] + [HttpPut] + [Authorize] + public async Task> UpsertAsync(TDto model) + { + if (!ModelState.IsValid) + { + return BadRequest(ModelState); + } + + var result = await this.baseDbService.Upsert(model); + return Ok(result); + } + + [HttpGet("{id}")] + public ActionResult GetById(TId id) + { + try + { + var result = this.baseDbService.GetById(id); + + if (result != null) + { + return result; + } + + return NotFound(); + } + catch (Exception error) + { + logger.LogError(error.Message); + return StatusCode(500); + } + } + + /// + /// Retrieves the total number of customers. + /// + /// Total count of customers as an integer. + [HttpGet("GetCount")] + public ActionResult GetCustomersCount() + { + return this.baseDbService.GetCount(); + } + } +} diff --git a/NorthwindCRUD/Controllers/CategoriesController.cs b/NorthwindCRUD/Controllers/CategoriesController.cs index c77775c..3920ba4 100644 --- a/NorthwindCRUD/Controllers/CategoriesController.cs +++ b/NorthwindCRUD/Controllers/CategoriesController.cs @@ -1,250 +1,251 @@ -namespace NorthwindCRUD.Controllers -{ - using AutoMapper; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using NorthwindCRUD.Models.DbModels; - using NorthwindCRUD.Models.Dtos; - using NorthwindCRUD.Services; - using Swashbuckle.AspNetCore.Annotations; - - [ApiController] - [Route("[controller]")] - public class CategoriesController : ControllerBase - { - private readonly CategoryService categoryService; - private readonly ProductService productService; - private readonly PagingService pagingService; - private readonly IMapper mapper; - private readonly ILogger logger; - - public CategoriesController(CategoryService categoryService, ProductService productService, PagingService pagingService, IMapper mapper, ILogger logger) - { - this.categoryService = categoryService; - this.productService = productService; - this.pagingService = pagingService; - this.mapper = mapper; - this.logger = logger; - } - - [HttpGet] - public ActionResult GetAll() - { - try - { - var categories = this.categoryService.GetAll(); - return Ok(this.mapper.Map(categories)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all categories or a page of categories based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the categories. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of categories to fetch. If this parameter is not provided, all categories are fetched. - /// A comma-separated list of fields to order the categories by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetCategoriesWithSkip")] - public ActionResult> GetCategoriesWithSkip( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve categories as Queryable - var categories = this.categoryService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(categories, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all categories or a page of categories based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. - /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetCategoriesWithPage")] - public ActionResult> GetCategoriesWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve categories as Queryable - var categories = this.categoryService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(categories, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Retrieves the total number of categories. - /// - /// Total count of categories as an integer. - [HttpGet("GetCategoriesCount")] - public ActionResult GetCategoriesCount() - { - try - { - var count = categoryService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}")] - public ActionResult GetById(int id) - { - try - { - var category = this.categoryService.GetById(id); - if (category != null) - { - return Ok(this.mapper.Map(category)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}/Details")] - public ActionResult GetDetailsById(int id) - { - try - { - var category = this.categoryService.GetById(id); - if (category != null) - { - return Ok(this.mapper.Map(category)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}/Products")] - public ActionResult GetProductsByCategoryId(int id) - { - try - { - var products = this.productService.GetAllByCategoryId(id); - return Ok(this.mapper.Map(products)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPost] - [Authorize] - public ActionResult Create(CategoryDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var category = this.categoryService.Create(mappedModel); - return Ok(this.mapper.Map(category)); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPut] - [Authorize] - public ActionResult Update(CategoryDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var category = this.categoryService.Update(mappedModel); - - if (category != null) - { - return Ok(this.mapper.Map(category)); - } - - return NotFound(); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpDelete("{id}")] - [Authorize] - public ActionResult Delete(int id) - { - try - { - var category = this.categoryService.Delete(id); - if (category != null) - { - return Ok(this.mapper.Map(category)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - } -} \ No newline at end of file +//namespace NorthwindCRUD.Controllers +//{ +// using AutoMapper; +// using Microsoft.AspNetCore.Authorization; +// using Microsoft.AspNetCore.Mvc; +// using NorthwindCRUD.Models.DbModels; +// using NorthwindCRUD.Models.Dtos; +// using NorthwindCRUD.Services; +// using Swashbuckle.AspNetCore.Annotations; + +// [ApiController] +// [Route("[controller]")] +// public class CategoriesController : BaseController +// { +// private readonly CategoryService categoryService; +// private readonly ProductService productService; +// private readonly PagingService pagingService; +// private readonly IMapper mapper; +// private readonly ILogger logger; + +// public CategoriesController(CategoryService categoryService, ProductService productService, PagingService pagingService, IMapper mapper, ILogger logger) +// : base(categoryService, logger) +// { +// this.categoryService = categoryService; +// this.productService = productService; +// this.pagingService = pagingService; +// this.mapper = mapper; +// this.logger = logger; +// } + +// [HttpGet] +// public ActionResult GetAll() +// { +// try +// { +// var categories = this.categoryService.GetAll(); +// return Ok(this.mapper.Map(categories)); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// /// +// /// Fetches all categories or a page of categories based on the provided parameters. +// /// +// /// The number of records to skip before starting to fetch the categories. If this parameter is not provided, fetching starts from the beginning. +// /// The maximum number of categories to fetch. If this parameter is not provided, all categories are fetched. +// /// A comma-separated list of fields to order the categories by, along with the sort direction (e.g., "field1 asc, field2 desc"). +// /// A PagedResultDto object containing the fetched T and the total record count. +// [HttpGet("GetCategoriesWithSkip")] +// public ActionResult> GetCategoriesWithSkip( +// [FromQuery][Attributes.SwaggerSkipParameter] int? skip, +// [FromQuery][Attributes.SwaggerTopParameter] int? top, +// [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) +// { +// try +// { +// // Retrieve categories as Queryable +// var categories = this.categoryService.GetAllAsQueryable(); + +// // Get paged data +// var pagedResult = pagingService.FetchPagedData(categories, skip, top, null, null, orderBy); + +// return Ok(pagedResult); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// /// +// /// Fetches all categories or a page of categories based on the provided parameters. +// /// +// /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). +// /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. +// /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). +// /// A PagedResultDto object containing the fetched T and the total record count. +// [HttpGet("GetCategoriesWithPage")] +// public ActionResult> GetCategoriesWithPage( +// [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, +// [FromQuery][Attributes.SwaggerSizeParameter] int? size, +// [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) +// { +// try +// { +// // Retrieve categories as Queryable +// var categories = this.categoryService.GetAllAsQueryable(); + +// // Get paged data +// var pagedResult = pagingService.FetchPagedData(categories, null, null, pageIndex, size, orderBy); + +// return Ok(pagedResult); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// /// +// /// Retrieves the total number of categories. +// /// +// /// Total count of categories as an integer. +// [HttpGet("GetCategoriesCount")] +// public ActionResult GetCategoriesCount() +// { +// try +// { +// var count = categoryService.GetAllAsQueryable().Count(); +// return new CountResultDto() { Count = count }; +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// [HttpGet("{id}")] +// public ActionResult GetById(int id) +// { +// try +// { +// var category = this.categoryService.GetById(id); +// if (category != null) +// { +// return Ok(this.mapper.Map(category)); +// } + +// return NotFound(); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// [HttpGet("{id}/Details")] +// public ActionResult GetDetailsById(int id) +// { +// try +// { +// var category = this.categoryService.GetById(id); +// if (category != null) +// { +// return Ok(this.mapper.Map(category)); +// } + +// return NotFound(); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// [HttpGet("{id}/Products")] +// public ActionResult GetProductsByCategoryId(int id) +// { +// try +// { +// var products = this.productService.GetAllByCategoryId(id); +// return Ok(this.mapper.Map(products)); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// [HttpPost] +// [Authorize] +// public ActionResult Create(CategoryDto model) +// { +// try +// { +// if (ModelState.IsValid) +// { +// var mappedModel = this.mapper.Map(model); +// var category = this.categoryService.Create(mappedModel); +// return Ok(this.mapper.Map(category)); +// } + +// return BadRequest(ModelState); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// [HttpPut] +// [Authorize] +// public ActionResult Update(CategoryDto model) +// { +// try +// { +// if (ModelState.IsValid) +// { +// var mappedModel = this.mapper.Map(model); +// var category = this.categoryService.Update(mappedModel); + +// if (category != null) +// { +// return Ok(this.mapper.Map(category)); +// } + +// return NotFound(); +// } + +// return BadRequest(ModelState); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } + +// [HttpDelete("{id}")] +// [Authorize] +// public ActionResult Delete(int id) +// { +// try +// { +// var category = this.categoryService.Delete(id); +// if (category != null) +// { +// return Ok(this.mapper.Map(category)); +// } + +// return NotFound(); +// } +// catch (Exception error) +// { +// logger.LogError(error.Message); +// return StatusCode(500); +// } +// } +// } +//} \ No newline at end of file diff --git a/NorthwindCRUD/Controllers/CustomersController.cs b/NorthwindCRUD/Controllers/CustomersController.cs index 9090df7..f17f295 100644 --- a/NorthwindCRUD/Controllers/CustomersController.cs +++ b/NorthwindCRUD/Controllers/CustomersController.cs @@ -1,231 +1,28 @@ namespace NorthwindCRUD.Controllers { using AutoMapper; - using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; using NorthwindCRUD.Services; - using Swashbuckle.AspNetCore.Annotations; [ApiController] [Route("[controller]")] - public class CustomersController : Controller + public class CustomersController : BaseController { - private readonly CustomerService customerService; private readonly OrderService orderService; - private readonly PagingService pagingService; - private readonly IMapper mapper; - private readonly ILogger logger; public CustomersController(CustomerService customerService, OrderService orderService, PagingService pagingService, IMapper mapper, ILogger logger) + : base(customerService, logger) { - this.customerService = customerService; this.orderService = orderService; - this.pagingService = pagingService; - this.mapper = mapper; - this.logger = logger; - } - - [HttpGet] - public ActionResult GetAll() - { - try - { - var customers = this.customerService.GetAll(); - return Ok(this.mapper.Map(customers)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all customers or a page of customers based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the customers. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of customers to fetch. If this parameter is not provided, all customers are fetched. - /// A comma-separated list of fields to order the customers by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetCustomersWithSkip")] - public ActionResult> GetCustomersWithSkip( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve all customers - var customers = this.customerService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(customers, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all customers or a page of customers based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. - /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetCustomersWithPage")] - public ActionResult> GetCustomersWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve customers as Queryable - var customers = this.customerService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(customers, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Retrieves the total number of customers. - /// - /// Total count of customers as an integer. - [HttpGet("GetCustomersCount")] - public ActionResult GetCustomersCount() - { - try - { - var count = customerService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}")] - public ActionResult GetById(string id) - { - try - { - var customer = this.customerService.GetById(id); - - if (customer != null) - { - return Ok(this.mapper.Map(customer)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } } [HttpGet("{id}/Orders")] public ActionResult GetOrdersByCustomerId(string id) { - try - { - var orders = this.orderService.GetOrdersByCustomerId(id); - return Ok(this.mapper.Map(orders)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPost] - [Authorize] - public ActionResult Create(CustomerDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var customer = this.customerService.Create(mappedModel); - return Ok(this.mapper.Map(customer)); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPut] - [Authorize] - public ActionResult Update(CustomerDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var customer = this.customerService.Update(mappedModel); - - if (customer != null) - { - return Ok(this.mapper.Map(customer)); - } - - return NotFound(); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpDelete("{id}")] - [Authorize] - public ActionResult Delete(string id) - { - try - { - var customer = this.customerService.Delete(id); - if (customer != null) - { - return Ok(this.mapper.Map(customer)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + var result = this.orderService.GetOrdersByCustomerId(id); + return Ok(result); } } -} +} \ No newline at end of file diff --git a/NorthwindCRUD/Controllers/OrdersController.cs b/NorthwindCRUD/Controllers/OrdersController.cs index acd1e5f..afa30bd 100644 --- a/NorthwindCRUD/Controllers/OrdersController.cs +++ b/NorthwindCRUD/Controllers/OrdersController.cs @@ -179,7 +179,7 @@ public ActionResult GetCustomerByOrderId(int id) if (customer != null) { - return this.mapper.Map(customer); + return customer; } } diff --git a/NorthwindCRUD/ControllersGraphQL/CustomerController.cs b/NorthwindCRUD/ControllersGraphQL/CustomerController.cs index af5d0a1..b723a0e 100644 --- a/NorthwindCRUD/ControllersGraphQL/CustomerController.cs +++ b/NorthwindCRUD/ControllersGraphQL/CustomerController.cs @@ -1,9 +1,7 @@ using AutoMapper; using GraphQL.AspNet.Attributes; using GraphQL.AspNet.Controllers; -using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; -using NorthwindCRUD.Models.InputModels; using NorthwindCRUD.Services; namespace NorthwindCRUD.Controllers @@ -12,63 +10,43 @@ namespace NorthwindCRUD.Controllers public class CustomerGraphController : GraphController { private readonly CustomerService customerService; - private readonly IMapper mapper; - private readonly ILogger logger; public CustomerGraphController(CustomerService customerService, IMapper mapper, ILogger logger) { this.customerService = customerService; - this.mapper = mapper; - this.logger = logger; } [Query] public CustomerDto[] GetAll() { var customers = this.customerService.GetAll(); - return this.mapper.Map(customers); + return customers; } [Query] public CustomerDto? GetById(string id) { var customer = this.customerService.GetById(id); - - if (customer != null) - { - return this.mapper.Map(customer); - } - - return null; + return customer; } [Mutation] - public CustomerDto Create(CustomerDto model) + public async Task Create(CustomerDto model) { - var mappedModel = this.mapper.Map(model); - var customer = this.customerService.Create(mappedModel); - return this.mapper.Map(customer); + return await this.customerService.Upsert(model); } [Mutation] - public CustomerDto? Update(CustomerDto model) + public async Task UpdateAsync(CustomerDto model) { - var mappedModel = this.mapper.Map(model); - var customer = this.customerService.Update(mappedModel); - return customer != null ? this.mapper.Map(customer) : null; + return await this.customerService.Upsert(model); } [Mutation] public CustomerDto? Delete(string id) { var customer = this.customerService.Delete(id); - - if (customer != null) - { - return this.mapper.Map(customer); - } - - return null; + return customer; } } } diff --git a/NorthwindCRUD/Models/DbModels/AddressDb.cs b/NorthwindCRUD/Models/DbModels/AddressDb.cs index 527ebb9..be7d33d 100644 --- a/NorthwindCRUD/Models/DbModels/AddressDb.cs +++ b/NorthwindCRUD/Models/DbModels/AddressDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class AddressDb : IAddress + public class AddressDb : IBaseDb, IAddress { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/CategoryDb.cs b/NorthwindCRUD/Models/DbModels/CategoryDb.cs index 14c737a..73b6555 100644 --- a/NorthwindCRUD/Models/DbModels/CategoryDb.cs +++ b/NorthwindCRUD/Models/DbModels/CategoryDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class CategoryDb : ICategory, ICategoryDetail + public class CategoryDb : IBaseDb, ICategory, ICategoryDetail { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/CustomerDb.cs b/NorthwindCRUD/Models/DbModels/CustomerDb.cs index 611b12f..8e9c667 100644 --- a/NorthwindCRUD/Models/DbModels/CustomerDb.cs +++ b/NorthwindCRUD/Models/DbModels/CustomerDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class CustomerDb : ICustomer + public class CustomerDb : IBaseDb, ICustomer { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] @@ -21,5 +21,10 @@ public class CustomerDb : ICustomer public AddressDb Address { get; set; } public ICollection Orders { get; set; } + + public string[] GetIncludes() + { + return new string[] { "Address" }; + } } } diff --git a/NorthwindCRUD/Models/DbModels/EmployeeDb.cs b/NorthwindCRUD/Models/DbModels/EmployeeDb.cs index 431e40a..a2376a5 100644 --- a/NorthwindCRUD/Models/DbModels/EmployeeDb.cs +++ b/NorthwindCRUD/Models/DbModels/EmployeeDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class EmployeeDb : IEmployee + public class EmployeeDb : IBaseDb, IEmployee { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/EmployeeTerritoryDb.cs b/NorthwindCRUD/Models/DbModels/EmployeeTerritoryDb.cs index f9e8e27..23f3b63 100644 --- a/NorthwindCRUD/Models/DbModels/EmployeeTerritoryDb.cs +++ b/NorthwindCRUD/Models/DbModels/EmployeeTerritoryDb.cs @@ -1,6 +1,6 @@ namespace NorthwindCRUD.Models.DbModels { - public class EmployeeTerritoryDb + public class EmployeeTerritoryDb : IBaseDb { public int EmployeeId { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/IBaseDb.cs b/NorthwindCRUD/Models/DbModels/IBaseDb.cs new file mode 100644 index 0000000..3f2d665 --- /dev/null +++ b/NorthwindCRUD/Models/DbModels/IBaseDb.cs @@ -0,0 +1,10 @@ +namespace NorthwindCRUD.Models.DbModels +{ + public interface IBaseDb + { + public string[] GetIncludes() + { + return Array.Empty(); + } + } +} diff --git a/NorthwindCRUD/Models/DbModels/OrderDb.cs b/NorthwindCRUD/Models/DbModels/OrderDb.cs index ccf9003..085bc05 100644 --- a/NorthwindCRUD/Models/DbModels/OrderDb.cs +++ b/NorthwindCRUD/Models/DbModels/OrderDb.cs @@ -3,11 +3,8 @@ namespace NorthwindCRUD.Models.DbModels { - public class OrderDb + public class OrderDb : IBaseDb { - public OrderDb() - { - } [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/OrderDetailDb.cs b/NorthwindCRUD/Models/DbModels/OrderDetailDb.cs index 8bf7391..b4a63ea 100644 --- a/NorthwindCRUD/Models/DbModels/OrderDetailDb.cs +++ b/NorthwindCRUD/Models/DbModels/OrderDetailDb.cs @@ -1,6 +1,6 @@ namespace NorthwindCRUD.Models.DbModels { - public class OrderDetailDb + public class OrderDetailDb : IBaseDb { public int OrderId { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/ProductDb.cs b/NorthwindCRUD/Models/DbModels/ProductDb.cs index 9cab5d4..6ab5c09 100644 --- a/NorthwindCRUD/Models/DbModels/ProductDb.cs +++ b/NorthwindCRUD/Models/DbModels/ProductDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class ProductDb : IProduct + public class ProductDb : IBaseDb, IProduct { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/RegionDb.cs b/NorthwindCRUD/Models/DbModels/RegionDb.cs index 241ef12..fc2b4fc 100644 --- a/NorthwindCRUD/Models/DbModels/RegionDb.cs +++ b/NorthwindCRUD/Models/DbModels/RegionDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class RegionDb : IRegion + public class RegionDb : IBaseDb, IRegion { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/ShipperDb.cs b/NorthwindCRUD/Models/DbModels/ShipperDb.cs index 583a785..7e9c567 100644 --- a/NorthwindCRUD/Models/DbModels/ShipperDb.cs +++ b/NorthwindCRUD/Models/DbModels/ShipperDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class ShipperDb : IShipper + public class ShipperDb : IBaseDb, IShipper { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/SupplierDb.cs b/NorthwindCRUD/Models/DbModels/SupplierDb.cs index 08cf742..87df7fb 100644 --- a/NorthwindCRUD/Models/DbModels/SupplierDb.cs +++ b/NorthwindCRUD/Models/DbModels/SupplierDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class SupplierDb : ISupplier + public class SupplierDb : IBaseDb, ISupplier { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/TerritoryDb.cs b/NorthwindCRUD/Models/DbModels/TerritoryDb.cs index ced7c21..51997e7 100644 --- a/NorthwindCRUD/Models/DbModels/TerritoryDb.cs +++ b/NorthwindCRUD/Models/DbModels/TerritoryDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class TerritoryDb : ITerritory + public class TerritoryDb : IBaseDb, ITerritory { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/DbModels/UserDb.cs b/NorthwindCRUD/Models/DbModels/UserDb.cs index 091b662..0a2a986 100644 --- a/NorthwindCRUD/Models/DbModels/UserDb.cs +++ b/NorthwindCRUD/Models/DbModels/UserDb.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.DbModels { - public class UserDb : IUser + public class UserDb : IBaseDb, IUser { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] diff --git a/NorthwindCRUD/Models/Dtos/AddressDto.cs b/NorthwindCRUD/Models/Dtos/AddressDto.cs index d117a5d..bce749f 100644 --- a/NorthwindCRUD/Models/Dtos/AddressDto.cs +++ b/NorthwindCRUD/Models/Dtos/AddressDto.cs @@ -2,7 +2,7 @@ { using NorthwindCRUD.Models.Contracts; - public class AddressDto : IAddress + public class AddressDto : IBaseDto, IAddress { public string Street { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/CategoryDetailsDto.cs b/NorthwindCRUD/Models/Dtos/CategoryDetailsDto.cs index c0b4f63..b1318ab 100644 --- a/NorthwindCRUD/Models/Dtos/CategoryDetailsDto.cs +++ b/NorthwindCRUD/Models/Dtos/CategoryDetailsDto.cs @@ -2,7 +2,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class CategoryDetailsDto : CategoryDto, ICategoryDetail + public class CategoryDetailsDto : CategoryDto, IBaseDto, ICategoryDetail { public string Picture { get; set; } } diff --git a/NorthwindCRUD/Models/Dtos/CategoryDto.cs b/NorthwindCRUD/Models/Dtos/CategoryDto.cs index f20b46e..05c2926 100644 --- a/NorthwindCRUD/Models/Dtos/CategoryDto.cs +++ b/NorthwindCRUD/Models/Dtos/CategoryDto.cs @@ -2,7 +2,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class CategoryDto : ICategory + public class CategoryDto : IBaseDto, ICategory { public int CategoryId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/CountResultDto.cs b/NorthwindCRUD/Models/Dtos/CountResultDto.cs index 5d4003d..cd3ea52 100644 --- a/NorthwindCRUD/Models/Dtos/CountResultDto.cs +++ b/NorthwindCRUD/Models/Dtos/CountResultDto.cs @@ -1,6 +1,6 @@ namespace NorthwindCRUD.Models.Dtos { - public class CountResultDto + public class CountResultDto : IBaseDto { public int Count { get; set; } } diff --git a/NorthwindCRUD/Models/Dtos/CustomerDto.cs b/NorthwindCRUD/Models/Dtos/CustomerDto.cs index 427c3d5..b415a56 100644 --- a/NorthwindCRUD/Models/Dtos/CustomerDto.cs +++ b/NorthwindCRUD/Models/Dtos/CustomerDto.cs @@ -3,7 +3,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class CustomerDto : ICustomer + public class CustomerDto : IBaseDto, ICustomer { public string CustomerId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/EmployeeDto.cs b/NorthwindCRUD/Models/Dtos/EmployeeDto.cs index 1dd99a4..a534f69 100644 --- a/NorthwindCRUD/Models/Dtos/EmployeeDto.cs +++ b/NorthwindCRUD/Models/Dtos/EmployeeDto.cs @@ -4,7 +4,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class EmployeeDto : IEmployee + public class EmployeeDto : IBaseDto, IEmployee { [SwaggerSchema("Number automatically assigned to new employee.")] [Required] diff --git a/NorthwindCRUD/Models/Dtos/EmployeeTerritoryDto.cs b/NorthwindCRUD/Models/Dtos/EmployeeTerritoryDto.cs index 1bab623..5a890cf 100644 --- a/NorthwindCRUD/Models/Dtos/EmployeeTerritoryDto.cs +++ b/NorthwindCRUD/Models/Dtos/EmployeeTerritoryDto.cs @@ -2,7 +2,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class EmployeeTerritoryDto : IEmployeeTerritory + public class EmployeeTerritoryDto : IBaseDto, IEmployeeTerritory { public int EmployeeId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/IBaseDto.cs b/NorthwindCRUD/Models/Dtos/IBaseDto.cs new file mode 100644 index 0000000..8175f89 --- /dev/null +++ b/NorthwindCRUD/Models/Dtos/IBaseDto.cs @@ -0,0 +1,6 @@ +namespace NorthwindCRUD.Models.Dtos +{ + public interface IBaseDto + { + } +} diff --git a/NorthwindCRUD/Models/Dtos/LoginDto.cs b/NorthwindCRUD/Models/Dtos/LoginDto.cs index f3f8648..1faf463 100644 --- a/NorthwindCRUD/Models/Dtos/LoginDto.cs +++ b/NorthwindCRUD/Models/Dtos/LoginDto.cs @@ -3,7 +3,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class LoginDto : IUser + public class LoginDto : IBaseDto, IUser { [EmailAddress] public string Email { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/OrderDetailDto.cs b/NorthwindCRUD/Models/Dtos/OrderDetailDto.cs index 148eb99..02927ef 100644 --- a/NorthwindCRUD/Models/Dtos/OrderDetailDto.cs +++ b/NorthwindCRUD/Models/Dtos/OrderDetailDto.cs @@ -1,6 +1,6 @@ namespace NorthwindCRUD.Models.Dtos { - public class OrderDetailDto + public class OrderDetailDto : IBaseDto { public int OrderId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/OrderDto.cs b/NorthwindCRUD/Models/Dtos/OrderDto.cs index b060588..1097371 100644 --- a/NorthwindCRUD/Models/Dtos/OrderDto.cs +++ b/NorthwindCRUD/Models/Dtos/OrderDto.cs @@ -2,7 +2,7 @@ { using NorthwindCRUD.Models.Contracts; - public class OrderDto : IOrder + public class OrderDto : IBaseDto, IOrder { public int OrderId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/ProductDto.cs b/NorthwindCRUD/Models/Dtos/ProductDto.cs index 6159499..57c2ad8 100644 --- a/NorthwindCRUD/Models/Dtos/ProductDto.cs +++ b/NorthwindCRUD/Models/Dtos/ProductDto.cs @@ -2,7 +2,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class ProductDto : IProduct + public class ProductDto : IBaseDto, IProduct { public int ProductId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/RegionDto.cs b/NorthwindCRUD/Models/Dtos/RegionDto.cs index 6cec254..27e05a3 100644 --- a/NorthwindCRUD/Models/Dtos/RegionDto.cs +++ b/NorthwindCRUD/Models/Dtos/RegionDto.cs @@ -2,7 +2,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class RegionDto : IRegion + public class RegionDto : IBaseDto, IRegion { public int RegionId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/RegisterDto.cs b/NorthwindCRUD/Models/Dtos/RegisterDto.cs index a17d7c5..2ba5841 100644 --- a/NorthwindCRUD/Models/Dtos/RegisterDto.cs +++ b/NorthwindCRUD/Models/Dtos/RegisterDto.cs @@ -3,7 +3,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class RegisterDto : IUser + public class RegisterDto : IBaseDto, IUser { [Required] [EmailAddress] diff --git a/NorthwindCRUD/Models/Dtos/SalesDto.cs b/NorthwindCRUD/Models/Dtos/SalesDto.cs index 4ee1096..6cb6b85 100644 --- a/NorthwindCRUD/Models/Dtos/SalesDto.cs +++ b/NorthwindCRUD/Models/Dtos/SalesDto.cs @@ -1,6 +1,6 @@ namespace NorthwindCRUD.Models.Dtos { - public class SalesDto + public class SalesDto : IBaseDto { public int ProductId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/ShipperDto.cs b/NorthwindCRUD/Models/Dtos/ShipperDto.cs index dff33fc..bad3862 100644 --- a/NorthwindCRUD/Models/Dtos/ShipperDto.cs +++ b/NorthwindCRUD/Models/Dtos/ShipperDto.cs @@ -2,7 +2,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class ShipperDto : IShipper + public class ShipperDto : IBaseDto, IShipper { public int ShipperId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/SupplierDto.cs b/NorthwindCRUD/Models/Dtos/SupplierDto.cs index 48c8913..1e3e577 100644 --- a/NorthwindCRUD/Models/Dtos/SupplierDto.cs +++ b/NorthwindCRUD/Models/Dtos/SupplierDto.cs @@ -2,7 +2,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class SupplierDto : ISupplier + public class SupplierDto : IBaseDto, ISupplier { public int SupplierId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/TerritoryDto.cs b/NorthwindCRUD/Models/Dtos/TerritoryDto.cs index 75570e2..22f0b72 100644 --- a/NorthwindCRUD/Models/Dtos/TerritoryDto.cs +++ b/NorthwindCRUD/Models/Dtos/TerritoryDto.cs @@ -2,7 +2,7 @@ namespace NorthwindCRUD.Models.Dtos { - public class TerritoryDto : ITerritory + public class TerritoryDto : IBaseDto, ITerritory { public string TerritoryId { get; set; } diff --git a/NorthwindCRUD/Program.cs b/NorthwindCRUD/Program.cs index 51a2dc4..08754d7 100644 --- a/NorthwindCRUD/Program.cs +++ b/NorthwindCRUD/Program.cs @@ -142,7 +142,7 @@ public static void Main(string[] args) builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); - builder.Services.AddTransient(); + builder.Services.AddTransient(); var app = builder.Build(); diff --git a/NorthwindCRUD/Services/BaseDbService.cs b/NorthwindCRUD/Services/BaseDbService.cs new file mode 100644 index 0000000..7b5abf8 --- /dev/null +++ b/NorthwindCRUD/Services/BaseDbService.cs @@ -0,0 +1,148 @@ +using System.ComponentModel.DataAnnotations; +using AutoMapper; +using Microsoft.EntityFrameworkCore; +using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; + +namespace NorthwindCRUD.Services +{ + public abstract class BaseDbService + where TDto : class, IBaseDto + where TDb : class, IBaseDb, new() + { + private readonly DataContext dataContext; + private readonly IMapper mapper; + private readonly IPagingService pagingService; + + public BaseDbService(DataContext dataContext, IMapper mapper, IPagingService pagingService) + { + this.dataContext = dataContext; + this.mapper = mapper; + this.pagingService = pagingService; + } + + public TDto[] GetAll() + { + TDb dtoInstance = new TDb(); + + IQueryable query = this.dataContext.Set(); + foreach (var include in dtoInstance.GetIncludes()) + { + query = query.Include(include); + } + + var dbResult = query.ToArray(); + return mapper.Map(dbResult); + } + + public IQueryable GetAllAsQueryable() + { + IQueryable query = this.dataContext.Set(); + return query; + } + + public TDto? GetById(TId id) + { + var dbResult = GetDbById(id); + + return mapper.Map(dbResult); + } + + public TDto? Delete(TId id) + { + var dbResult = GetDbById(id); + if (dbResult == null) + { + return null; + } + + this.dataContext.Remove(dbResult); + this.dataContext.SaveChanges(); + return mapper.Map(dbResult); + } + + private TDb GetDbById(TId id) + { + TDb dtoInstance = new TDb(); + + IQueryable query = this.dataContext.Set(); + foreach (var include in dtoInstance.GetIncludes()) + { + query = query.Include(include); + } + + var keyProperty = typeof(TDb).GetProperties() + .FirstOrDefault(p => Attribute.IsDefined(p, typeof(KeyAttribute))); + + if (keyProperty == null) + { + throw new Exception("No key property found on entity"); + } + + TDb? dbResult = query.FirstOrDefault(entity => + EF.Property(entity, keyProperty.Name).Equals(id)); + + return dbResult; + } + + public PagedResultDto GetWithPageSkip(int? skip = null, int? top = null, int? pageIndex = null, int? size = null, string? orderBy = null) + { + var query = GetAllAsQueryable(); + + var pagedResult = pagingService.FetchPagedData(query, skip, top, pageIndex, size, orderBy); + + return pagedResult; + } + + public async Task Upsert(TDto model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + // Find the key property using reflection (assumes you have a KeyAttribute defined) + var keyProperty = typeof(TDb).GetProperties() + .FirstOrDefault(p => Attribute.IsDefined(p, typeof(KeyAttribute))); + + if (keyProperty == null) + { + throw new InvalidOperationException($"Entity {typeof(TDb).Name} has no key property defined."); + } + + // Assuming your DTO has a property named "Id" that corresponds to the primary key + var dtoId = (int?)keyProperty.GetValue(model); + + if (model == null || dtoId == 0) + { + // New entity (insert) + var newEntity = mapper.Map(model); + await dataContext.Set().AddAsync(newEntity); + await dataContext.SaveChangesAsync(); + var mappedResult = mapper.Map(newEntity); + return mappedResult; + } + else + { + var existingEntity = await dataContext.Set().FindAsync(dtoId); + if (existingEntity == null) + { + throw new Exception($"Entity with id {dtoId} not found."); + } + + mapper.Map(model, existingEntity, opts => opts.Items["IsPatch"] = true); + await dataContext.SaveChangesAsync(); + var mappedResult = mapper.Map(existingEntity); + return mappedResult; + } + } + + public CountResultDto GetCount() + { + return new CountResultDto() + { + Count = this.dataContext.Set().Count(), + }; + } + } +} diff --git a/NorthwindCRUD/Services/CategoryService.cs b/NorthwindCRUD/Services/CategoryService.cs index 67e8986..84e5934 100644 --- a/NorthwindCRUD/Services/CategoryService.cs +++ b/NorthwindCRUD/Services/CategoryService.cs @@ -1,33 +1,21 @@ namespace NorthwindCRUD.Services { - using Microsoft.EntityFrameworkCore; + using AutoMapper; using NorthwindCRUD.Helpers; using NorthwindCRUD.Models.DbModels; + using NorthwindCRUD.Models.Dtos; - public class CategoryService + public class CategoryService : BaseDbService { private readonly DataContext dataContext; + private readonly IPagingService pagingService; - public CategoryService(DataContext dataContext) + public CategoryService(DataContext dataContext, IPagingService pagingService, IMapper mapper) + : base(dataContext, mapper, pagingService) { this.dataContext = dataContext; } - public CategoryDb[] GetAll() - { - return this.dataContext.Categories.ToArray(); - } - - public IQueryable GetAllAsQueryable() - { - return this.dataContext.Categories; - } - - public CategoryDb? GetById(int id) - { - return this.dataContext.Categories.FirstOrDefault(c => c.CategoryId == id); - } - public CategoryDb Create(CategoryDb model) { var id = IdGenerator.CreateDigitsId(); @@ -47,32 +35,5 @@ public CategoryDb Create(CategoryDb model) return categoryEntity.Entity; } - - public CategoryDb? Update(CategoryDb model) - { - var categoryEntity = this.dataContext.Categories.FirstOrDefault(c => c.CategoryId == model.CategoryId); - if (categoryEntity != null) - { - categoryEntity.Description = model.Description != null ? model.Description : categoryEntity.Description; - categoryEntity.Name = model.Name != null ? model.Name : categoryEntity.Name; - categoryEntity.Picture = model.Picture != null ? model.Picture : categoryEntity.Picture; - - this.dataContext.SaveChanges(); - } - - return categoryEntity; - } - - public CategoryDb? Delete(int id) - { - var categoryEntity = this.GetById(id); - if (categoryEntity != null) - { - this.dataContext.Categories.Remove(categoryEntity); - this.dataContext.SaveChanges(); - } - - return categoryEntity; - } } } diff --git a/NorthwindCRUD/Services/CustomerService.cs b/NorthwindCRUD/Services/CustomerService.cs index 98cc993..5d600d4 100644 --- a/NorthwindCRUD/Services/CustomerService.cs +++ b/NorthwindCRUD/Services/CustomerService.cs @@ -1,114 +1,12 @@ -using Microsoft.EntityFrameworkCore; -using NorthwindCRUD.Helpers; +using AutoMapper; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { - public class CustomerService + public class CustomerService : BaseDbService { - private readonly DataContext dataContext; - - public CustomerService(DataContext dataContext) - { - this.dataContext = dataContext; - } - - public CustomerDb[] GetAll() - { - return this.dataContext.Customers - .Include(c => c.Address) - .ToArray(); - } - - public IQueryable GetAllAsQueryable() - { - return this.dataContext.Customers; - } - - public CustomerDb? GetById(string id) - { - return this.dataContext.Customers - .Include(c => c.Address) - .FirstOrDefault(c => c.CustomerId == id); - } - - public CustomerDb Create(CustomerDb model) - { - var id = IdGenerator.CreateLetterId(6); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateLetterId(6); - existWithId = this.GetById(id); - } - - model.CustomerId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - if (model.Address == null) - { - var emptyAddress = this.dataContext.Addresses.FirstOrDefault(a => a.Street == string.Empty); - if (emptyAddress != null) - { - model.Address = emptyAddress; - model.AddressId = emptyAddress.AddressId; - } - } - - var customerEntity = this.dataContext.Customers.Add(model); - this.dataContext.SaveChanges(); - - return customerEntity.Entity; - } - - public CustomerDb? Update(CustomerDb model) - { - var customerEntity = this.dataContext.Customers - .Include(c => c.Address) - .FirstOrDefault(c => c.CustomerId == model.CustomerId); - - if (customerEntity != null) - { - customerEntity.CompanyName = model.CompanyName != null ? model.CompanyName : customerEntity.CompanyName; - customerEntity.ContactName = model.ContactName != null ? model.ContactName : customerEntity.ContactName; - customerEntity.ContactTitle = model.ContactTitle != null ? model.ContactTitle : customerEntity.ContactTitle; - - if (model.Address != null) - { - var newAddress = this.dataContext.Addresses.FirstOrDefault(a => a.Street == model.Address.Street); - if (newAddress != null) - { - customerEntity.Address.City = model.Address.City != null ? model.Address.City : customerEntity.Address.City; - customerEntity.Address.Region = model.Address.Region != null ? model.Address.Region : customerEntity.Address.Region; - customerEntity.Address.PostalCode = model.Address.PostalCode != null ? model.Address.PostalCode : customerEntity.Address.PostalCode; - customerEntity.Address.Country = model.Address.Country != null ? model.Address.Country : customerEntity.Address.Country; - customerEntity.Address.Phone = model.Address.Phone != null ? model.Address.Phone : customerEntity.Address.Phone; - } - else - { - var customerNewAddress = this.dataContext.Addresses.Add(model.Address); - customerEntity.Address = customerNewAddress.Entity; - customerEntity.AddressId = customerNewAddress.Entity.AddressId; - } - } - - this.dataContext.SaveChanges(); - } - - return customerEntity; - } - - public CustomerDb? Delete(string id) - { - var customerEntity = this.GetById(id); - if (customerEntity != null) - { - this.dataContext.Customers.Remove(customerEntity); - this.dataContext.SaveChanges(); - } - - return customerEntity; - } + public CustomerService(DataContext dataContext, IMapper mapper, IPagingService pagingService) + : base(dataContext, mapper, pagingService) { } } } diff --git a/NorthwindCRUD/Services/OrderService.cs b/NorthwindCRUD/Services/OrderService.cs index 0341e82..431fbbd 100644 --- a/NorthwindCRUD/Services/OrderService.cs +++ b/NorthwindCRUD/Services/OrderService.cs @@ -1,19 +1,23 @@ using System.Globalization; +using AutoMapper; using Microsoft.CodeAnalysis; using Microsoft.EntityFrameworkCore; using NorthwindCRUD.Constants; using NorthwindCRUD.Helpers; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { public class OrderService { private readonly DataContext dataContext; + private readonly IMapper mapper; - public OrderService(DataContext dataContext) + public OrderService(DataContext dataContext, IMapper mapper) { this.dataContext = dataContext; + this.mapper = mapper; } public OrderDb[] GetAll() @@ -47,11 +51,11 @@ public OrderDetailDb[] GetOrderDetailsById(int id) return details; } - public OrderDb[] GetOrdersByCustomerId(string id) + public OrderDto[] GetOrdersByCustomerId(string id) { - return GetOrdersQuery() + return mapper.Map(GetOrdersQuery() .Where(o => o.CustomerId == id) - .ToArray(); + .ToArray()); } public OrderDb[] GetOrdersByEmployeeId(int id) From 8281021851b43b4816137f1b6e4c9fd4b4b0bd3c Mon Sep 17 00:00:00 2001 From: Dimitar Georgiev Dimitrov Date: Wed, 23 Oct 2024 17:15:10 +0300 Subject: [PATCH 2/5] task(*): refactoring --- NorthwindCRUD.Tests/BaseFixture.cs | 12 +- NorthwindCRUD.Tests/CategroyServiceFixture.cs | 20 +- NorthwindCRUD.Tests/CustomerServiceFixture.cs | 50 +- NorthwindCRUD.Tests/EmployeeServiceFixture.cs | 35 +- .../EmployeeTerritoryServiceFixture.cs | 22 +- NorthwindCRUD.Tests/Helpers/DataHelper.cs | 149 ++- NorthwindCRUD.Tests/OrderServiceFixture.cs | 42 +- NorthwindCRUD.Tests/ProductServiceFixture.cs | 24 +- NorthwindCRUD.Tests/RegionServiceFixture.cs | 27 +- NorthwindCRUD.Tests/SalesServiceFixture.cs | 25 +- NorthwindCRUD.Tests/ShipperServiceFixture.cs | 29 +- NorthwindCRUD.Tests/SupplierServiceFixture.cs | 41 +- .../TerritoryServiceFixture.cs | 24 +- .../Attributes/SwaggerParameterAttributes.cs | 50 +- NorthwindCRUD/Constants/StringTemplates.cs | 4 +- NorthwindCRUD/Controllers/BaseController.cs | 106 +- .../Controllers/CategoriesController.cs | 296 +---- .../Controllers/CustomersController.cs | 6 +- .../Controllers/EmployeesController.cs | 276 +---- NorthwindCRUD/Controllers/OrdersController.cs | 332 +---- .../Controllers/ProductsController.cs | 273 +---- .../Controllers/RegionsController.cs | 218 +--- NorthwindCRUD/Controllers/SalesController.cs | 6 +- .../Controllers/ShippersController.cs | 215 +--- .../Controllers/SuppliersController.cs | 213 +--- .../Controllers/TerritoriesController.cs | 256 +--- .../ControllersGraphQL/CategoryController.cs | 33 +- .../ControllersGraphQL/CustomerController.cs | 11 +- .../ControllersGraphQL/EmployeeController.cs | 40 +- .../ControllersGraphQL/OrderController.cs | 36 +- NorthwindCRUD/DataContext.cs | 20 +- NorthwindCRUD/Helpers/DBSeeder.cs | 24 +- NorthwindCRUD/Helpers/MappingProfiles.cs | 84 +- ...41022072605_TablesToOwnAddress.Designer.cs | 610 ++++++++++ .../20241022072605_TablesToOwnAddress.cs | 1084 +++++++++++++++++ .../Migrations/DataContextModelSnapshot.cs | 559 +++++++-- NorthwindCRUD/Models/Contracts/IAddress.cs | 4 +- NorthwindCRUD/Models/Contracts/ICategory.cs | 2 +- NorthwindCRUD/Models/Contracts/ICustomer.cs | 6 +- NorthwindCRUD/Models/Contracts/IEmployee.cs | 6 +- .../Models/Contracts/IEmployeeTerritory.cs | 2 - NorthwindCRUD/Models/Contracts/IOrder.cs | 6 +- NorthwindCRUD/Models/Contracts/IProduct.cs | 2 +- NorthwindCRUD/Models/Contracts/IRegion.cs | 2 +- NorthwindCRUD/Models/Contracts/IShipper.cs | 6 +- NorthwindCRUD/Models/Contracts/ISupplier.cs | 2 +- NorthwindCRUD/Models/DbModels/AddressDb.cs | 13 +- NorthwindCRUD/Models/DbModels/CategoryDb.cs | 2 +- NorthwindCRUD/Models/DbModels/CustomerDb.cs | 9 +- NorthwindCRUD/Models/DbModels/EmployeeDb.cs | 4 +- NorthwindCRUD/Models/DbModels/OrderDb.cs | 5 +- NorthwindCRUD/Models/DbModels/ProductDb.cs | 2 +- NorthwindCRUD/Models/DbModels/RegionDb.cs | 2 +- NorthwindCRUD/Models/DbModels/ShipperDb.cs | 2 +- NorthwindCRUD/Models/DbModels/SupplierDb.cs | 2 +- NorthwindCRUD/Models/DbModels/TerritoryDb.cs | 2 +- NorthwindCRUD/Models/Dtos/CategoryDto.cs | 4 +- NorthwindCRUD/Models/Dtos/CustomerDto.cs | 1 + NorthwindCRUD/Models/Dtos/EmployeeDto.cs | 3 +- .../Models/Dtos/EmployeeTerritoryDto.cs | 2 + NorthwindCRUD/Models/Dtos/OrderDto.cs | 2 + NorthwindCRUD/Models/Dtos/ProductDto.cs | 4 +- NorthwindCRUD/Models/Dtos/RegionDto.cs | 4 +- NorthwindCRUD/Models/Dtos/ShipperDto.cs | 4 +- NorthwindCRUD/Models/Dtos/SupplierDto.cs | 4 +- NorthwindCRUD/Models/Dtos/TerritoryDto.cs | 4 +- NorthwindCRUD/Services/BaseDbService.cs | 84 +- NorthwindCRUD/Services/CategoryService.cs | 27 +- NorthwindCRUD/Services/CustomerService.cs | 2 +- NorthwindCRUD/Services/EmployeeService.cs | 119 +- .../Services/EmployeeTerritoryService.cs | 24 +- NorthwindCRUD/Services/OrderService.cs | 174 +-- NorthwindCRUD/Services/ProductService.cs | 116 +- NorthwindCRUD/Services/RegionService.cs | 70 +- NorthwindCRUD/Services/SalesService.cs | 2 +- NorthwindCRUD/Services/ShipperService.cs | 72 +- NorthwindCRUD/Services/SupplierService.cs | 81 +- NorthwindCRUD/Services/TerritoryService.cs | 88 +- 78 files changed, 2984 insertions(+), 3240 deletions(-) create mode 100644 NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.Designer.cs create mode 100644 NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.cs diff --git a/NorthwindCRUD.Tests/BaseFixture.cs b/NorthwindCRUD.Tests/BaseFixture.cs index 3bcbe48..084b9d3 100644 --- a/NorthwindCRUD.Tests/BaseFixture.cs +++ b/NorthwindCRUD.Tests/BaseFixture.cs @@ -1,7 +1,9 @@ using System.Data.Common; +using AutoMapper; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; +using NorthwindCRUD.Services; namespace NorthwindCRUD.Tests { @@ -17,13 +19,19 @@ public class BaseFixture [TestInitialize] public void Initialize() { + var mappingConfigs = new MapperConfiguration(cfg => + { + cfg.AddProfile(); + }); + var mapper = mappingConfigs.CreateMapper(); + var pagingService = new PagingService(mapper); DataContext context = GetInMemoryDatabaseContext(); DataContext context2 = GetInMemoryDatabaseContext(); Assert.AreNotEqual(context.GetHashCode(), context2.GetHashCode(), "Contexts instances should be different."); Assert.AreEqual(context.Database.GetDbConnection(), context2.Database.GetDbConnection(), "Contexts instances should have the same database connection."); - DataHelper = new DataHelper(context); - DataHelper2 = new DataHelper(context2); + DataHelper = new DataHelper(context, pagingService, mapper); + DataHelper2 = new DataHelper(context2, pagingService, mapper); } protected DataContext GetInMemoryDatabaseContext() diff --git a/NorthwindCRUD.Tests/CategroyServiceFixture.cs b/NorthwindCRUD.Tests/CategroyServiceFixture.cs index 95de263..8f2b693 100644 --- a/NorthwindCRUD.Tests/CategroyServiceFixture.cs +++ b/NorthwindCRUD.Tests/CategroyServiceFixture.cs @@ -6,10 +6,10 @@ namespace NorthwindCRUD.Tests public class CategoryServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateCategory() + public async Task ShouldCreateCategory() { var category = DataHelper.GetCategory(); - var createdCategory = DataHelper.CategoryService.Create(category); + var createdCategory = await DataHelper.CategoryService.Create(category); Assert.IsNotNull(createdCategory); createdCategory = DataHelper2.CategoryService.GetById(createdCategory.CategoryId); @@ -19,16 +19,16 @@ public void ShouldCreateCategory() } [TestMethod] - public void ShouldUpdateCategory() + public async Task ShouldUpdateCategory() { var category = DataHelper.GetCategory(); string orignalName = category.Name; string orignalDescription = category.Description; - var createdCategory = DataHelper.CategoryService.Create(category); + var createdCategory = await DataHelper.CategoryService.Create(category); createdCategory.Name = "Updated Category"; createdCategory.Description = "Updated Description"; - var updatedCategory = DataHelper.CategoryService.Update(createdCategory); + var updatedCategory = await DataHelper.CategoryService.Update(createdCategory, createdCategory.CategoryId); Assert.IsNotNull(updatedCategory); updatedCategory = DataHelper2.CategoryService.GetById(updatedCategory.CategoryId); @@ -40,11 +40,11 @@ public void ShouldUpdateCategory() } [TestMethod] - public void ShouldDeleteCategory() + public async Task ShouldDeleteCategory() { var category = DataHelper.GetCategory(); - var createdCategory = DataHelper.CategoryService.Create(category); + var createdCategory = await DataHelper.CategoryService.Create(category); DataHelper.CategoryService.Delete(createdCategory.CategoryId); var deletedCategory = DataHelper2.CategoryService.GetById(createdCategory.CategoryId); @@ -53,10 +53,10 @@ public void ShouldDeleteCategory() } [TestMethod] - public void ShouldReturnAllCategories() + public async Task ShouldReturnAllCategories() { - DataHelper.CategoryService.Create(DataHelper.GetCategory()); - DataHelper.CategoryService.Create(DataHelper.GetCategory()); + await DataHelper.CategoryService.Create(DataHelper.GetCategory()); + await DataHelper.CategoryService.Create(DataHelper.GetCategory()); var result = DataHelper2.CategoryService.GetAll(); Assert.IsNotNull(result); diff --git a/NorthwindCRUD.Tests/CustomerServiceFixture.cs b/NorthwindCRUD.Tests/CustomerServiceFixture.cs index 6a85951..773bd21 100644 --- a/NorthwindCRUD.Tests/CustomerServiceFixture.cs +++ b/NorthwindCRUD.Tests/CustomerServiceFixture.cs @@ -6,36 +6,42 @@ namespace NorthwindCRUD.Tests public class CustomerServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateCustomer() + public async Task ShouldCreateCustomer() { - //var customer = DataHelper.GetCustomer(); - //var createdCustomer = DataHelper.CustomerService.Create(customer); - //Assert.IsNotNull(createdCustomer); - //Assert.AreEqual(customer, createdCustomer, "Customers instances should be the same since we are over the same context"); + var customer = DataHelper.GetCustomer(); + var createdCustomer = await DataHelper.CustomerService.Create(customer); + Assert.IsNotNull(createdCustomer); + Assert.AreEqual(customer.CompanyName, createdCustomer.CompanyName); + Assert.AreEqual(customer.ContactName, createdCustomer.ContactName); + Assert.AreEqual(customer.ContactTitle, createdCustomer.ContactTitle); + Assert.AreEqual(customer.Address.Street, createdCustomer.Address.Street); + Assert.AreEqual(customer.Address.City, createdCustomer.Address.City); + Assert.AreEqual(customer.Address.PostalCode, createdCustomer.Address.PostalCode); + Assert.AreEqual(customer.Address.Country, createdCustomer.Address.Country); + Assert.AreEqual(customer.Address.Phone, createdCustomer.Address.Phone); - ////createdCustomer = DataHelper2.CustomerService.GetById(createdCustomer.CustomerId); - //Assert.IsNotNull(createdCustomer); - //Assert.AreNotEqual(customer, createdCustomer, "Customer instances should be different"); + createdCustomer = DataHelper2.CustomerService.GetById(createdCustomer.CustomerId); + Assert.IsNotNull(createdCustomer); - //Assert.AreEqual(customer.CompanyName, createdCustomer.CompanyName); - //Assert.AreEqual(customer.ContactName, createdCustomer.ContactName); - //Assert.AreEqual(customer.ContactTitle, createdCustomer.ContactTitle); - //Assert.AreEqual(customer.Address.Street, createdCustomer.Address.Street); - //Assert.AreEqual(customer.Address.City, createdCustomer.Address.City); - //Assert.AreEqual(customer.Address.PostalCode, createdCustomer.Address.PostalCode); - //Assert.AreEqual(customer.Address.Country, createdCustomer.Address.Country); - //Assert.AreEqual(customer.Address.Phone, createdCustomer.Address.Phone); + Assert.AreEqual(customer.CompanyName, createdCustomer.CompanyName); + Assert.AreEqual(customer.ContactName, createdCustomer.ContactName); + Assert.AreEqual(customer.ContactTitle, createdCustomer.ContactTitle); + Assert.AreEqual(customer.Address.Street, createdCustomer.Address.Street); + Assert.AreEqual(customer.Address.City, createdCustomer.Address.City); + Assert.AreEqual(customer.Address.PostalCode, createdCustomer.Address.PostalCode); + Assert.AreEqual(customer.Address.Country, createdCustomer.Address.Country); + Assert.AreEqual(customer.Address.Phone, createdCustomer.Address.Phone); } [TestMethod] - public void ShouldReturnAllCustomers() + public async Task ShouldReturnAllCustomers() { - //DataHelper.CustomerService.Create(DataHelper.GetCustomer()); - //DataHelper.CustomerService.Create(DataHelper.GetCustomer()); + await DataHelper.CustomerService.Create(DataHelper.GetCustomer()); + await DataHelper.CustomerService.Create(DataHelper.GetCustomer()); - //var result = DataHelper2.CustomerService.GetAll(); - //Assert.IsNotNull(result); - //Assert.AreEqual(2, result.Length); + var result = DataHelper2.CustomerService.GetAll(); + Assert.IsNotNull(result); + Assert.AreEqual(2, result.Length); } } } \ No newline at end of file diff --git a/NorthwindCRUD.Tests/EmployeeServiceFixture.cs b/NorthwindCRUD.Tests/EmployeeServiceFixture.cs index 832881f..d699c7a 100644 --- a/NorthwindCRUD.Tests/EmployeeServiceFixture.cs +++ b/NorthwindCRUD.Tests/EmployeeServiceFixture.cs @@ -1,5 +1,4 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NorthwindCRUD.Models.DbModels; namespace NorthwindCRUD.Tests { @@ -7,11 +6,11 @@ namespace NorthwindCRUD.Tests public class EmployeeServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateEmployee() + public async Task ShouldCreateEmployee() { - EmployeeDb employee = DataHelper.GetEmployee(); + var employee = DataHelper.GetEmployee(); - var createdEmployee = DataHelper.EmployeeService.Create(employee); + var createdEmployee = await DataHelper.EmployeeService.Create(employee); Assert.IsNotNull(createdEmployee); createdEmployee = DataHelper2.EmployeeService.GetById(createdEmployee.EmployeeId); @@ -22,14 +21,14 @@ public void ShouldCreateEmployee() } [TestMethod] - public void ShouldUpdateEmployee() + public async Task ShouldUpdateEmployee() { var employee = DataHelper.GetEmployee(); string originalTitle = employee.Title; - var createdEmployee = DataHelper.EmployeeService.Create(employee); + var createdEmployee = await DataHelper.EmployeeService.Create(employee); createdEmployee.Title = "Director"; - var updatedEmployee = DataHelper.EmployeeService.Update(createdEmployee); + var updatedEmployee = await DataHelper.EmployeeService.Update(createdEmployee, createdEmployee.EmployeeId); Assert.IsNotNull(updatedEmployee); updatedEmployee = DataHelper2.EmployeeService.GetById(updatedEmployee.EmployeeId); @@ -39,10 +38,10 @@ public void ShouldUpdateEmployee() } [TestMethod] - public void ShouldDeleteEmployee() + public async Task ShouldDeleteEmployee() { var employee = DataHelper.GetEmployee(); - var createdEmployee = DataHelper.EmployeeService.Create(employee); + var createdEmployee = await DataHelper.EmployeeService.Create(employee); DataHelper.EmployeeService.Delete(createdEmployee.EmployeeId); var deletedEmployee = DataHelper2.EmployeeService.GetById(createdEmployee.EmployeeId); @@ -51,10 +50,10 @@ public void ShouldDeleteEmployee() } [TestMethod] - public void ShouldReturnAllEmployees() + public async Task ShouldReturnAllEmployees() { - DataHelper.EmployeeService.Create(DataHelper.GetEmployee()); - DataHelper.EmployeeService.Create(DataHelper.GetEmployee()); + await DataHelper.EmployeeService.Create(DataHelper.GetEmployee()); + await DataHelper.EmployeeService.Create(DataHelper.GetEmployee()); var result = DataHelper2.EmployeeService.GetAll(); @@ -63,19 +62,19 @@ public void ShouldReturnAllEmployees() } [TestMethod] - public void ShouldReturnEmployeesByReportsTo() + public async Task ShouldReturnEmployeesByReportsTo() { var manager = DataHelper.GetEmployee(); - var createdManager = DataHelper.EmployeeService.Create(manager); + var createdManager = await DataHelper.EmployeeService.Create(manager); var employee1 = DataHelper.GetEmployee(); employee1.ReportsTo = createdManager.EmployeeId; var employee2 = DataHelper.GetEmployee(); employee2.ReportsTo = createdManager.EmployeeId; - var createdEmployee1 = DataHelper.EmployeeService.Create(employee1); - var createdEmployee2 = DataHelper.EmployeeService.Create(employee2); + var createdEmployee1 = await DataHelper.EmployeeService.Create(employee1); + var createdEmployee2 = await DataHelper.EmployeeService.Create(employee2); var result = DataHelper.EmployeeService.GetEmployeesByReportsTo(createdManager.EmployeeId); Assert.IsNotNull(result); @@ -84,11 +83,11 @@ public void ShouldReturnEmployeesByReportsTo() } [TestMethod] - public void ShouldReturnEmployeeById() + public async Task ShouldReturnEmployeeById() { var employee = DataHelper.GetEmployee(); - var createdEmployee = DataHelper.EmployeeService.Create(employee); + var createdEmployee = await DataHelper.EmployeeService.Create(employee); var result = DataHelper.EmployeeService.GetById(createdEmployee.EmployeeId); diff --git a/NorthwindCRUD.Tests/EmployeeTerritoryServiceFixture.cs b/NorthwindCRUD.Tests/EmployeeTerritoryServiceFixture.cs index eb9fc78..d3c6088 100644 --- a/NorthwindCRUD.Tests/EmployeeTerritoryServiceFixture.cs +++ b/NorthwindCRUD.Tests/EmployeeTerritoryServiceFixture.cs @@ -6,10 +6,10 @@ namespace NorthwindCRUD.Tests public class EmployeeTerritoryServiceFixture : BaseFixture { [TestMethod] - public void ShouldAddTerritoryToEmployee() + public async Task ShouldAddTerritoryToEmployee() { - var employeeId = DataHelper.CreateEmployee().EmployeeId; - var territoryId = DataHelper.CreateTerritory().TerritoryId; + var employeeId = (await DataHelper.CreateEmployee()).EmployeeId; + var territoryId = (await DataHelper.CreateTerritory()).TerritoryId; DataHelper.CreateEmployeeTerritory(employeeId, territoryId); @@ -19,11 +19,11 @@ public void ShouldAddTerritoryToEmployee() } [TestMethod] - public void ShouldReturnTerritoriesForEmployee() + public async Task ShouldReturnTerritoriesForEmployee() { - var employeeId = DataHelper.CreateEmployee().EmployeeId; - var territoryId1 = DataHelper.CreateTerritory().TerritoryId; - var territoryId2 = DataHelper.CreateTerritory().TerritoryId; + var employeeId = (await DataHelper.CreateEmployee()).EmployeeId; + var territoryId1 = (await DataHelper.CreateTerritory()).TerritoryId; + var territoryId2 = (await DataHelper.CreateTerritory()).TerritoryId; DataHelper.CreateEmployeeTerritory(employeeId, territoryId1); DataHelper.CreateEmployeeTerritory(employeeId, territoryId2); @@ -37,11 +37,11 @@ public void ShouldReturnTerritoriesForEmployee() } [TestMethod] - public void ShouldReturnEmployeesForTerritory() + public async Task ShouldReturnEmployeesForTerritory() { - var territoryId = DataHelper.CreateTerritory().TerritoryId; - var employeeId1 = DataHelper.CreateEmployee().EmployeeId; - var employeeId2 = DataHelper.CreateEmployee().EmployeeId; + var territoryId = (await DataHelper.CreateTerritory()).TerritoryId; + var employeeId1 = (await DataHelper.CreateEmployee()).EmployeeId; + var employeeId2 = (await DataHelper.CreateEmployee()).EmployeeId; DataHelper.CreateEmployeeTerritory(employeeId1, territoryId); DataHelper.CreateEmployeeTerritory(employeeId2, territoryId); diff --git a/NorthwindCRUD.Tests/Helpers/DataHelper.cs b/NorthwindCRUD.Tests/Helpers/DataHelper.cs index 202a8a3..583c68d 100644 --- a/NorthwindCRUD.Tests/Helpers/DataHelper.cs +++ b/NorthwindCRUD.Tests/Helpers/DataHelper.cs @@ -1,7 +1,9 @@ using System.Reflection; +using AutoMapper; +using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; -using NorthwindCRUD.Models.Contracts; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; using NorthwindCRUD.Services; namespace NorthwindCRUD.Tests @@ -9,20 +11,22 @@ namespace NorthwindCRUD.Tests public class DataHelper { private DataContext dataContext; + private IMapper mapper; - public DataHelper(DataContext dataContext) + public DataHelper(DataContext dataContext, IPagingService pagingService, IMapper mapper) { + this.mapper = mapper; this.dataContext = dataContext; - //CategoryService = new CategoryService(dataContext); - //CustomerService = new CustomerService(dataContext); - EmployeeService = new EmployeeService(dataContext); - ProductService = new ProductService(dataContext); - SupplierService = new SupplierService(dataContext); - RegionService = new RegionService(dataContext); - TerritoryService = new TerritoryService(dataContext); - //OrderService = new OrderService(dataContext); - ShipperService = new ShipperService(dataContext); - EmployeeTerritoryService = new EmployeeTerritoryService(dataContext); + CustomerService = new CustomerService(dataContext, pagingService, mapper); + EmployeeService = new EmployeeService(dataContext, pagingService, mapper); + ProductService = new ProductService(dataContext, pagingService, mapper); + SupplierService = new SupplierService(dataContext, pagingService, mapper); + RegionService = new RegionService(dataContext, pagingService, mapper); + TerritoryService = new TerritoryService(dataContext, pagingService, mapper); + OrderService = new OrderService(dataContext, pagingService, mapper); + ShipperService = new ShipperService(dataContext, pagingService, mapper); + EmployeeTerritoryService = new EmployeeTerritoryService(dataContext, mapper); + CategoryService = new CategoryService(dataContext, pagingService, mapper); SalesService = new SalesService(dataContext); } @@ -48,83 +52,106 @@ public DataHelper(DataContext dataContext) public EmployeeTerritoryService EmployeeTerritoryService { get; set; } - internal static CategoryDb GetCategory() + internal CategoryDto GetCategory() { - return GetJsonContent("categories.json").GetRandomElement(); + var categores = GetJsonContent("categories.json").GetRandomElement(); + return mapper.Map(categores); } - internal static CustomerDb GetCustomer() + internal CustomerDto GetCustomer() { - return GetJsonContent("customers.json").GetRandomElement(); + var customer = GetJsonContent("customers.json").GetRandomElement(); + return mapper.Map(customer); } - internal static EmployeeDb GetEmployee() + internal EmployeeDto GetEmployee() { - return GetJsonContent("employees.json").GetRandomElement(); + var employee = GetJsonContent("employees.json").GetRandomElement(); + return mapper.Map(employee); } - internal static ProductDb GetProduct() + internal ProductDto GetProduct() { - return GetJsonContent("products.json").GetRandomElement(); + var product = GetJsonContent("products.json").GetRandomElement(); + return mapper.Map(product); } - internal static SupplierDb GetSupplier() + internal SupplierDto GetSupplier() { - return GetJsonContent("suppliers.json").GetRandomElement(); + var supplier = GetJsonContent("suppliers.json").GetRandomElement(); + return mapper.Map(supplier); } - internal static ShipperDb GetShipper() + internal ShipperDto GetShipper() { - return GetJsonContent("shippers.json").GetRandomElement(); + var shipper = GetJsonContent("shippers.json").GetRandomElement(); + return mapper.Map(shipper); } - internal static TerritoryDb GetTerritory() + internal TerritoryDto GetTerritory() { - return GetJsonContent("territories.json").GetRandomElement(); + var territory = GetJsonContent("territories.json").GetRandomElement(); + return mapper.Map(territory); } - internal static RegionDb GetRegion() + internal RegionDto GetRegion() { - return GetJsonContent("regions.json").GetRandomElement(); + var region = GetJsonContent("regions.json").GetRandomElement(); + return mapper.Map(region); } - internal OrderDb GetOrder() + internal OrderDto GetOrder() { - return GetJsonContent("orders.json").GetRandomElement(); + var order = GetJsonContent("orders.json").GetRandomElement(); + return mapper.Map(order); } - internal OrderDetailDb GetOrderDetail() + internal OrderDetailDto GetOrderDetail() { - return GetJsonContent("orderDetails.json").GetRandomElement(); + var orderDetail = GetJsonContent("orderDetails.json").GetRandomElement(); + return mapper.Map(orderDetail); } - internal SupplierDb CreateSupplier() + + internal async Task CreateSupplier() { - return SupplierService.Create(GetSupplier()); + var supplier = GetSupplier(); + var createdSupplier = await SupplierService.Create(supplier); + dataContext.Entry(mapper.Map(createdSupplier)).State = EntityState.Detached; + return createdSupplier; } - internal ShipperDb CreateShipper() + internal async Task CreateShipper() { - return ShipperService.Create(GetShipper()); + var shipper = GetShipper(); + var createdShipper = await ShipperService.Create(shipper); + dataContext.Entry(mapper.Map(createdShipper)).State = EntityState.Detached; + return createdShipper; } - internal RegionDb CreateRegion() + internal async Task CreateRegion() { - return RegionService.Create(GetRegion()); + var region = GetRegion(); + var createdRegion = await RegionService.Create(region); + dataContext.Entry(mapper.Map(createdRegion)).State = EntityState.Detached; + return createdRegion; } - internal CustomerDb CreateCustomer() + internal async Task CreateCustomer() { - return null; - //return CustomerService.Create(GetCustomer()); + var customer = GetCustomer(); + var createdCustomer = await CustomerService.Create(customer); + dataContext.Entry(mapper.Map(createdCustomer)).State = EntityState.Detached; + return createdCustomer; } - internal OrderDb CreateOrder(string? orderDate = null, string? country = null, ProductDb? product = null, int? quantity = null) + + internal async Task CreateOrder(string? orderDate = null, string? country = null, ProductDto? product = null, int? quantity = null) { var order = GetOrder(); - var customer = CreateCustomer(); - var employee = CreateEmployee(); - var shipper = CreateShipper(); + var customer = await CreateCustomer(); + var employee = await CreateEmployee(); + var shipper = await CreateShipper(); order.CustomerId = customer.CustomerId; order.EmployeeId = employee.EmployeeId; order.ShipperId = shipper.ShipperId; @@ -136,7 +163,7 @@ internal OrderDb CreateOrder(string? orderDate = null, string? country = null, P if (country != null) { - order.ShipAddress = new AddressDb + order.ShipAddress = new AddressDto { Country = country, Street = string.Empty, @@ -146,13 +173,13 @@ internal OrderDb CreateOrder(string? orderDate = null, string? country = null, P }; } - OrderDb result = OrderService.Create(order); - OrderDetailDb details = GetOrderDetail(); + var result = await OrderService.Create(order); + var details = GetOrderDetail(); details.OrderId = result.OrderId; if (product == null) { - product = CreateProduct(); + product = await CreateProduct(); } if (quantity != null) @@ -162,48 +189,48 @@ internal OrderDb CreateOrder(string? orderDate = null, string? country = null, P details.ProductId = product.ProductId; - this.dataContext.Add(details); + this.dataContext.Add(mapper.Map(details)); this.dataContext.SaveChanges(); return result; } - internal ProductDb CreateProduct(ProductDb? product = null) + internal async Task CreateProduct(ProductDto? product = null) { if (product == null) { product = GetProduct(); } - var createdCategory = CategoryService.Create(DataHelper.GetCategory()); + var createdCategory = await CategoryService.Create(GetCategory()); product.CategoryId = createdCategory.CategoryId; - var createdSupplier = SupplierService.Create(DataHelper.GetSupplier()); + var createdSupplier = await SupplierService.Create(GetSupplier()); product.SupplierId = createdSupplier.SupplierId; - return ProductService.Create(product); + return await ProductService.Create(product); } - internal EmployeeDb CreateEmployee() + internal async Task CreateEmployee() { - return EmployeeService.Create(GetEmployee()); + return await EmployeeService.Create(GetEmployee()); } - internal TerritoryDb CreateTerritory(TerritoryDb? territory = null) + internal async Task CreateTerritory(TerritoryDto? territory = null) { if (territory == null) { territory = GetTerritory(); } - RegionDb region = CreateRegion(); + var region = await CreateRegion(); territory.RegionId = region.RegionId; - return TerritoryService.Create(territory); + return await TerritoryService.Create(territory); } - internal EmployeeTerritoryDb CreateEmployeeTerritory(int employeeId, string territoryId) + internal EmployeeTerritoryDto CreateEmployeeTerritory(int employeeId, string territoryId) { - var employeeTerritory = new EmployeeTerritoryDb + var employeeTerritory = new EmployeeTerritoryDto { EmployeeId = employeeId, TerritoryId = territoryId, diff --git a/NorthwindCRUD.Tests/OrderServiceFixture.cs b/NorthwindCRUD.Tests/OrderServiceFixture.cs index 67aebc7..81ff3da 100644 --- a/NorthwindCRUD.Tests/OrderServiceFixture.cs +++ b/NorthwindCRUD.Tests/OrderServiceFixture.cs @@ -6,38 +6,44 @@ namespace NorthwindCRUD.Tests public class OrderServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateOrder() + public async Task ShouldCreateOrder() { var order = DataHelper.GetOrder(); - var customer = DataHelper.CreateCustomer(); - var employee = DataHelper.CreateEmployee(); - var shipper = DataHelper.CreateShipper(); + var customer = await DataHelper.CreateCustomer(); + var employee = await DataHelper.CreateEmployee(); + var shipper = await DataHelper.CreateShipper(); order.CustomerId = customer.CustomerId; order.EmployeeId = employee.EmployeeId; order.ShipperId = shipper.ShipperId; - var createdOrder = DataHelper.OrderService.Create(order); + var createdOrder = await DataHelper.OrderService.Create(order); Assert.IsNotNull(createdOrder); createdOrder = DataHelper2.OrderService.GetById(createdOrder.OrderId); Assert.IsNotNull(createdOrder); - Assert.AreEqual(order.OrderId, createdOrder.OrderId); Assert.AreEqual(order.CustomerId, createdOrder.CustomerId); Assert.AreEqual(order.EmployeeId, createdOrder.EmployeeId); + Assert.AreEqual(order.ShipperId, createdOrder.ShipperId); + Assert.AreEqual(order.OrderDate, createdOrder.OrderDate); + Assert.AreEqual(order.RequiredDate, createdOrder.RequiredDate); + Assert.AreEqual(order.ShipVia, createdOrder.ShipVia); + Assert.AreEqual(order.Freight, createdOrder.Freight); + Assert.AreEqual(order.ShipName, createdOrder.ShipName); + Assert.AreEqual(order.ShipAddress.City, createdOrder.ShipAddress.City); } [TestMethod] - public void ShouldUpdateOrder() + public async Task ShouldUpdateOrder() { - var order = DataHelper.CreateOrder(); + var order = await DataHelper.CreateOrder(); string? originalCustomerId = order.CustomerId; int? originalEmployeeId = order.EmployeeId; - order.CustomerId = DataHelper.CreateCustomer().CustomerId; - order.EmployeeId = DataHelper.CreateEmployee().EmployeeId; + order.CustomerId = (await DataHelper.CreateCustomer()).CustomerId; + order.EmployeeId = (await DataHelper.CreateEmployee()).EmployeeId; - var updatedOrder = DataHelper.OrderService.Update(order); + var updatedOrder = await DataHelper.OrderService.Update(order, order.OrderId); Assert.IsNotNull(updatedOrder); updatedOrder = DataHelper2.OrderService.GetById(updatedOrder.OrderId); @@ -49,9 +55,9 @@ public void ShouldUpdateOrder() } [TestMethod] - public void ShouldDeleteOrder() + public async Task ShouldDeleteOrder() { - var order = DataHelper.CreateOrder(); + var order = await DataHelper.CreateOrder(); DataHelper.OrderService.Delete(order.OrderId); var deletedOrder = DataHelper2.OrderService.GetById(order.OrderId); @@ -60,10 +66,10 @@ public void ShouldDeleteOrder() } [TestMethod] - public void ShouldGetAllOrders() + public async Task ShouldGetAllOrders() { - DataHelper.CreateOrder(); - DataHelper.CreateOrder(); + await DataHelper.CreateOrder(); + await DataHelper.CreateOrder(); var result = DataHelper2.OrderService.GetAll(); @@ -72,9 +78,9 @@ public void ShouldGetAllOrders() } [TestMethod] - public void ShouldGetOrderById() + public async Task ShouldGetOrderById() { - var order = DataHelper.CreateOrder(); + var order = await DataHelper.CreateOrder(); var result = DataHelper2.OrderService.GetById(order.OrderId); diff --git a/NorthwindCRUD.Tests/ProductServiceFixture.cs b/NorthwindCRUD.Tests/ProductServiceFixture.cs index d3be0ba..426e4e1 100644 --- a/NorthwindCRUD.Tests/ProductServiceFixture.cs +++ b/NorthwindCRUD.Tests/ProductServiceFixture.cs @@ -6,10 +6,10 @@ namespace NorthwindCRUD.Tests public class ProductServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateProduct() + public async Task ShouldCreateProduct() { var product = DataHelper.GetProduct(); - var createdProduct = DataHelper.CreateProduct(product); + var createdProduct = await DataHelper.CreateProduct(product); Assert.IsNotNull(createdProduct); createdProduct = DataHelper2.ProductService.GetById(createdProduct.ProductId); @@ -19,15 +19,15 @@ public void ShouldCreateProduct() } [TestMethod] - public void ShouldUpdateProduct() + public async Task ShouldUpdateProduct() { - var createdProduct = DataHelper.CreateProduct(); + var createdProduct = await DataHelper.CreateProduct(); double? originaUnitPrice = createdProduct.UnitPrice; double? originaUnitsInStock = createdProduct.UnitsInStock; createdProduct.UnitPrice = 15; createdProduct.UnitsInStock = 50; - var updatedProduct = DataHelper.ProductService.Update(createdProduct); + var updatedProduct = await DataHelper.ProductService.Update(createdProduct, createdProduct.ProductId); Assert.IsNotNull(updatedProduct); updatedProduct = DataHelper2.ProductService.GetById(updatedProduct.ProductId); @@ -40,9 +40,9 @@ public void ShouldUpdateProduct() } [TestMethod] - public void ShouldDeleteProduct() + public async Task ShouldDeleteProduct() { - var createdProduct = DataHelper.CreateProduct(); + var createdProduct = await DataHelper.CreateProduct(); DataHelper.ProductService.Delete(createdProduct.ProductId); var deletedProduct = DataHelper2.ProductService.GetById(createdProduct.ProductId); @@ -51,10 +51,10 @@ public void ShouldDeleteProduct() } [TestMethod] - public void ShouldGetAllProducts() + public async Task ShouldGetAllProducts() { - DataHelper.CreateProduct(); - DataHelper.CreateProduct(); + await DataHelper.CreateProduct(); + await DataHelper.CreateProduct(); var result = DataHelper2.ProductService.GetAll(); @@ -63,9 +63,9 @@ public void ShouldGetAllProducts() } [TestMethod] - public void ShouldGetProductById() + public async Task ShouldGetProductById() { - var createdProduct = DataHelper.CreateProduct(); + var createdProduct = await DataHelper.CreateProduct(); var result = DataHelper2.ProductService.GetById(createdProduct.ProductId); Assert.IsNotNull(result); diff --git a/NorthwindCRUD.Tests/RegionServiceFixture.cs b/NorthwindCRUD.Tests/RegionServiceFixture.cs index f263088..4daac2e 100644 --- a/NorthwindCRUD.Tests/RegionServiceFixture.cs +++ b/NorthwindCRUD.Tests/RegionServiceFixture.cs @@ -1,5 +1,4 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NorthwindCRUD.Models.DbModels; namespace NorthwindCRUD.Tests { @@ -7,27 +6,27 @@ namespace NorthwindCRUD.Tests public class RegionServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateRegion() + public async Task ShouldCreateRegion() { var region = DataHelper.GetRegion(); - var createdRegion = DataHelper.RegionService.Create(region); + var createdRegion = await DataHelper.RegionService.Create(region); Assert.IsNotNull(createdRegion); createdRegion = DataHelper2.RegionService.GetById(createdRegion.RegionId); Assert.IsNotNull(createdRegion); - Assert.AreEqual(region.RegionId, createdRegion.RegionId); Assert.AreEqual(region.RegionDescription, createdRegion.RegionDescription); + } [TestMethod] - public void ShouldUpdateRegion() + public async Task ShouldUpdateRegion() { - var region = DataHelper.CreateRegion(); + var region = await DataHelper.CreateRegion(); string originalRegionDescription = region.RegionDescription; region.RegionDescription = "Updated Region"; - var updatedRegion = DataHelper.RegionService.Update(region); + var updatedRegion = await DataHelper.RegionService.Update(region, region.RegionId); Assert.IsNotNull(updatedRegion); updatedRegion = DataHelper2.RegionService.GetById(updatedRegion.RegionId); @@ -37,9 +36,9 @@ public void ShouldUpdateRegion() } [TestMethod] - public void ShouldDeleteRegion() + public async Task ShouldDeleteRegion() { - var region = DataHelper.CreateRegion(); + var region = await DataHelper.CreateRegion(); DataHelper.RegionService.Delete(region.RegionId); var deletedRegion = DataHelper2.RegionService.GetById(region.RegionId); @@ -48,10 +47,10 @@ public void ShouldDeleteRegion() } [TestMethod] - public void ShouldGetAllRegions() + public async Task ShouldGetAllRegions() { - DataHelper.CreateRegion(); - DataHelper.CreateRegion(); + await DataHelper.CreateRegion(); + await DataHelper.CreateRegion(); var result = DataHelper2.RegionService.GetAll(); @@ -60,9 +59,9 @@ public void ShouldGetAllRegions() } [TestMethod] - public void ShouldGetByRegionId() + public async Task ShouldGetByRegionId() { - var region = DataHelper.CreateRegion(); + var region = await DataHelper.CreateRegion(); var result = DataHelper2.RegionService.GetById(region.RegionId); diff --git a/NorthwindCRUD.Tests/SalesServiceFixture.cs b/NorthwindCRUD.Tests/SalesServiceFixture.cs index 5dcb3bb..31d9836 100644 --- a/NorthwindCRUD.Tests/SalesServiceFixture.cs +++ b/NorthwindCRUD.Tests/SalesServiceFixture.cs @@ -7,10 +7,10 @@ namespace NorthwindCRUD.Tests public class SalesServiceFixture : BaseFixture { [TestMethod] - public void ShouldRetrieveSalesDataByYear() + public async Task ShouldRetrieveSalesDataByYear() { - var order1 = DataHelper.CreateOrder("2023-10-10T00:00:00"); - var order2 = DataHelper.CreateOrder("2023-01-01T00:00:00"); + var order1 = await DataHelper.CreateOrder("2023-10-10T00:00:00"); + var order2 = await DataHelper.CreateOrder("2023-01-01T00:00:00"); SalesDto[] salesData = DataHelper2.SalesService.RetrieveSalesDataByYear(2023, 0, 0); @@ -27,10 +27,10 @@ public void ShouldRetrieveSalesDataByYear() } [TestMethod] - public void ShouldRetrieveSalesDataByCountry() + public async Task ShouldRetrieveSalesDataByCountry() { - var order2 = DataHelper.CreateOrder("2023-01-01T00:00:00", "USA"); - var order1 = DataHelper.CreateOrder("2023-10-10T00:00:00", "USA"); + var order2 = await DataHelper.CreateOrder("2023-01-01T00:00:00", "USA"); + var order1 = await DataHelper.CreateOrder("2023-10-10T00:00:00", "USA"); SalesDto[] salesData = DataHelper.SalesService.RetrieveSalesDataByCountry("2023-01-01", "2023-12-31", "USA"); @@ -51,13 +51,16 @@ public void ShouldRetrieveSalesDataByCountry() } [TestMethod] - public void ShouldRetrieveSalesDataByProductCategoryAndYear() + public async Task ShouldRetrieveSalesDataByProductCategoryAndYear() { - var product = DataHelper.CreateProduct(); - var order2 = DataHelper.CreateOrder("2023-01-01T00:00:00", product: product, quantity: 10); - var order1 = DataHelper.CreateOrder("2023-10-10T00:00:00", product: product, quantity: 20); + var product = await DataHelper.CreateProduct(); + var order2 = await DataHelper.CreateOrder("2023-01-01T00:00:00", product: product, quantity: 10); + var order1 = await DataHelper.CreateOrder("2023-10-10T00:00:00", product: product, quantity: 20); - SalesDto[] salesData = DataHelper2.SalesService.GetSalesDataByCategoryAndYear(product.Category!.Name, 2023); + Assert.IsNotNull(product.CategoryId); + + var category = DataHelper2.CategoryService.GetById((int)product.CategoryId); + SalesDto[] salesData = DataHelper2.SalesService.GetSalesDataByCategoryAndYear(category.Name, 2023); Assert.IsNotNull(salesData); Assert.AreEqual(2, salesData.Length); diff --git a/NorthwindCRUD.Tests/ShipperServiceFixture.cs b/NorthwindCRUD.Tests/ShipperServiceFixture.cs index eb6713a..6b91a2c 100644 --- a/NorthwindCRUD.Tests/ShipperServiceFixture.cs +++ b/NorthwindCRUD.Tests/ShipperServiceFixture.cs @@ -6,32 +6,31 @@ namespace NorthwindCRUD.Tests public class ShipperServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateShipper() + public async Task ShouldCreateShipper() { var shipper = DataHelper.GetShipper(); - var createdShipper = DataHelper.ShipperService.Create(shipper); + var createdShipper = await DataHelper.ShipperService.Create(shipper); Assert.IsNotNull(createdShipper); createdShipper = DataHelper2.ShipperService.GetById(createdShipper.ShipperId); Assert.IsNotNull(createdShipper); - Assert.AreEqual(shipper.ShipperId, createdShipper.ShipperId); Assert.AreEqual(shipper.CompanyName, createdShipper.CompanyName); Assert.AreEqual(shipper.Phone, createdShipper.Phone); } [TestMethod] - public void ShouldUpdateShipper() + public async Task ShouldUpdateShipper() { var shipper = DataHelper.GetShipper(); string originalCompanyName = shipper.CompanyName; string originalPhone = shipper.Phone; - DataHelper.ShipperService.Create(shipper); + var insertedShipper = await DataHelper.ShipperService.Create(shipper); shipper.CompanyName = "Updated shipper company"; shipper.Phone = "555-555-5555"; - var updatedShipper = DataHelper.ShipperService.Update(shipper); + var updatedShipper = await DataHelper.ShipperService.Update(shipper, insertedShipper.ShipperId); Assert.IsNotNull(updatedShipper); updatedShipper = DataHelper2.ShipperService.GetById(updatedShipper.ShipperId); @@ -43,10 +42,10 @@ public void ShouldUpdateShipper() } [TestMethod] - public void ShouldDeleteShipper() + public async Task ShouldDeleteShipper() { var shipper = DataHelper.GetShipper(); - DataHelper.ShipperService.Create(shipper); + await DataHelper.ShipperService.Create(shipper); DataHelper.ShipperService.Delete(shipper.ShipperId); var deletedShipper = DataHelper2.ShipperService.GetById(shipper.ShipperId); @@ -55,10 +54,10 @@ public void ShouldDeleteShipper() } [TestMethod] - public void ShouldGetAllShippers() + public async Task ShouldGetAllShippers() { - DataHelper.CreateShipper(); - DataHelper.CreateShipper(); + await DataHelper.CreateShipper(); + await DataHelper.CreateShipper(); var result = DataHelper2.ShipperService.GetAll(); @@ -67,15 +66,15 @@ public void ShouldGetAllShippers() } [TestMethod] - public void ShouldGetShipperById() + public async Task ShouldGetShipperById() { var shipper = DataHelper.GetShipper(); - DataHelper.ShipperService.Create(shipper); + var insertedShipper = await DataHelper.ShipperService.Create(shipper); - var result = DataHelper2.ShipperService.GetById(shipper.ShipperId); + var result = DataHelper2.ShipperService.GetById(insertedShipper.ShipperId); Assert.IsNotNull(result); - Assert.AreEqual(shipper.ShipperId, result.ShipperId); + Assert.AreEqual(insertedShipper.ShipperId, result.ShipperId); Assert.AreEqual(shipper.CompanyName, result.CompanyName); Assert.AreEqual(shipper.Phone, result.Phone); } diff --git a/NorthwindCRUD.Tests/SupplierServiceFixture.cs b/NorthwindCRUD.Tests/SupplierServiceFixture.cs index 60357af..37ae853 100644 --- a/NorthwindCRUD.Tests/SupplierServiceFixture.cs +++ b/NorthwindCRUD.Tests/SupplierServiceFixture.cs @@ -1,5 +1,4 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NorthwindCRUD.Models.DbModels; namespace NorthwindCRUD.Tests { @@ -7,47 +6,46 @@ namespace NorthwindCRUD.Tests public class SupplierServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateSupplier() + public async Task ShouldCreateSupplier() { var supplier = DataHelper.GetSupplier(); - var createdSupplier = DataHelper.SupplierService.Create(supplier); + var createdSupplier = await DataHelper.SupplierService.Create(supplier); Assert.IsNotNull(createdSupplier); createdSupplier = DataHelper2.SupplierService.GetById(createdSupplier.SupplierId); Assert.IsNotNull(createdSupplier); - Assert.AreEqual(supplier.SupplierId, createdSupplier.SupplierId); Assert.AreEqual(supplier.CompanyName, createdSupplier.CompanyName); Assert.AreEqual(supplier.ContactName, createdSupplier.ContactName); } [TestMethod] - public void ShouldUpdateSupplier() + public async Task ShouldUpdateSupplier() { var supplier = DataHelper.GetSupplier(); string? originalCompanyName = supplier.CompanyName; string? originalContactName = supplier.ContactName; string? originalContactTitle = supplier.ContactTitle; - DataHelper.SupplierService.Create(supplier); + var insertedSupplier = await DataHelper.SupplierService.Create(supplier); - supplier.CompanyName = "Updated Supplier"; - supplier.ContactName = "Updated Contact"; - supplier.ContactTitle = "Updated Title"; + insertedSupplier.CompanyName = "Updated Supplier"; + insertedSupplier.ContactName = "Updated Contact"; + insertedSupplier.ContactTitle = "Updated Title"; - var updatedSupplier = DataHelper.SupplierService.Update(supplier); + var updatedSupplier = await DataHelper.SupplierService.Update(insertedSupplier, insertedSupplier.SupplierId); Assert.IsNotNull(updatedSupplier); updatedSupplier = DataHelper2.SupplierService.GetById(updatedSupplier.SupplierId); Assert.IsNotNull(updatedSupplier); - Assert.AreEqual(supplier.CompanyName, updatedSupplier.CompanyName); - Assert.AreEqual(supplier.ContactName, updatedSupplier.ContactName); - Assert.AreEqual(supplier.ContactTitle, updatedSupplier.ContactTitle); + Assert.AreEqual(insertedSupplier.CompanyName, updatedSupplier.CompanyName); + Assert.AreEqual(insertedSupplier.ContactName, updatedSupplier.ContactName); + Assert.AreEqual(insertedSupplier.ContactTitle, updatedSupplier.ContactTitle); } [TestMethod] - public void ShouldDeleteSupplier() + public async Task ShouldDeleteSupplier() { var supplier = DataHelper.GetSupplier(); - DataHelper.SupplierService.Create(supplier); + await DataHelper.SupplierService.Create(supplier); DataHelper.SupplierService.Delete(supplier.SupplierId); var deletedSupplier = DataHelper2.SupplierService.GetById(supplier.SupplierId); @@ -56,10 +54,10 @@ public void ShouldDeleteSupplier() } [TestMethod] - public void ShouldGetAllSuppliers() + public async Task ShouldGetAllSuppliers() { - DataHelper.CreateSupplier(); - DataHelper.CreateSupplier(); + await DataHelper.CreateSupplier(); + await DataHelper.CreateSupplier(); var result = DataHelper2.SupplierService.GetAll(); @@ -68,15 +66,14 @@ public void ShouldGetAllSuppliers() } [TestMethod] - public void ShouldGetBySupplierId() + public async Task ShouldGetBySupplierId() { var supplier = DataHelper.GetSupplier(); - DataHelper.SupplierService.Create(supplier); + var insertedSupplier = await DataHelper.SupplierService.Create(supplier); - var result = DataHelper2.SupplierService.GetById(supplier.SupplierId); + var result = DataHelper2.SupplierService.GetById(insertedSupplier.SupplierId); Assert.IsNotNull(result); - Assert.AreEqual(supplier.SupplierId, result.SupplierId); Assert.AreEqual(supplier.CompanyName, result.CompanyName); Assert.AreEqual(supplier.ContactName, result.ContactName); } diff --git a/NorthwindCRUD.Tests/TerritoryServiceFixture.cs b/NorthwindCRUD.Tests/TerritoryServiceFixture.cs index 4747dc3..5300150 100644 --- a/NorthwindCRUD.Tests/TerritoryServiceFixture.cs +++ b/NorthwindCRUD.Tests/TerritoryServiceFixture.cs @@ -6,11 +6,11 @@ namespace NorthwindCRUD.Tests public class TerritoryServiceFixture : BaseFixture { [TestMethod] - public void ShouldCreateTerritory() + public async Task ShouldCreateTerritory() { var territory = DataHelper.GetTerritory(); - var createdTerritory = DataHelper.CreateTerritory(territory); + var createdTerritory = await DataHelper.CreateTerritory(territory); Assert.IsNotNull(createdTerritory); createdTerritory = DataHelper2.TerritoryService.GetById(createdTerritory.TerritoryId); @@ -21,15 +21,15 @@ public void ShouldCreateTerritory() } [TestMethod] - public void ShouldUpdateTerritory() + public async Task ShouldUpdateTerritory() { var territory = DataHelper.GetTerritory(); string originalTerritoryDescription = territory.TerritoryDescription; - var createdTerritory = DataHelper.CreateTerritory(territory); + var createdTerritory = await DataHelper.CreateTerritory(territory); createdTerritory.TerritoryDescription = "Updated Territory"; - var updatedTerritory = DataHelper.TerritoryService.Update(createdTerritory); + var updatedTerritory = await DataHelper.TerritoryService.Update(createdTerritory, createdTerritory.TerritoryId); Assert.IsNotNull(updatedTerritory); updatedTerritory = DataHelper2.TerritoryService.GetById(updatedTerritory.TerritoryId); @@ -39,9 +39,9 @@ public void ShouldUpdateTerritory() } [TestMethod] - public void ShouldDeleteTerritory() + public async Task ShouldDeleteTerritory() { - var territory = DataHelper.CreateTerritory(); + var territory = await DataHelper.CreateTerritory(); DataHelper.TerritoryService.Delete(territory.TerritoryId); var deletedTerritory = DataHelper2.TerritoryService.GetById(territory.TerritoryId); @@ -49,10 +49,10 @@ public void ShouldDeleteTerritory() } [TestMethod] - public void ShouldReturnAllTerritories() + public async Task ShouldReturnAllTerritories() { - DataHelper.CreateTerritory(); - DataHelper.CreateTerritory(); + await DataHelper.CreateTerritory(); + await DataHelper.CreateTerritory(); var result = DataHelper2.TerritoryService.GetAll(); @@ -61,9 +61,9 @@ public void ShouldReturnAllTerritories() } [TestMethod] - public void ShouldReturnTerritory() + public async Task ShouldReturnTerritory() { - var territory = DataHelper.CreateTerritory(); + var territory = await DataHelper.CreateTerritory(); var result = DataHelper2.TerritoryService.GetById(territory.TerritoryId); diff --git a/NorthwindCRUD/Attributes/SwaggerParameterAttributes.cs b/NorthwindCRUD/Attributes/SwaggerParameterAttributes.cs index 45bded8..b2a05a0 100644 --- a/NorthwindCRUD/Attributes/SwaggerParameterAttributes.cs +++ b/NorthwindCRUD/Attributes/SwaggerParameterAttributes.cs @@ -2,43 +2,43 @@ namespace NorthwindCRUD.Attributes { - public class SwaggerPageParameterAttribute : SwaggerParameterAttribute + public class SwaggerPageParameterAttribute : SwaggerParameterAttribute + { + public SwaggerPageParameterAttribute() + : base("The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0).") { - public SwaggerPageParameterAttribute() - : base("The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0).") - { - } } + } - public class SwaggerSizeParameterAttribute : SwaggerParameterAttribute + public class SwaggerSizeParameterAttribute : SwaggerParameterAttribute + { + public SwaggerSizeParameterAttribute() + : base("The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched.") { - public SwaggerSizeParameterAttribute() - : base("The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched.") - { - } } + } - public class SwaggerOrderByParameterAttribute : SwaggerParameterAttribute + public class SwaggerOrderByParameterAttribute : SwaggerParameterAttribute + { + public SwaggerOrderByParameterAttribute() + : base("A comma-separated list of fields to order the records by, along with the sort direction (e.g., 'field1 asc, field2 desc').") { - public SwaggerOrderByParameterAttribute() - : base("A comma-separated list of fields to order the records by, along with the sort direction (e.g., 'field1 asc, field2 desc').") - { - } } + } - public class SwaggerSkipParameterAttribute : SwaggerParameterAttribute + public class SwaggerSkipParameterAttribute : SwaggerParameterAttribute + { + public SwaggerSkipParameterAttribute() + : base("The number of records to skip before starting to fetch them. If this parameter is not provided, fetching starts from the beginning.") { - public SwaggerSkipParameterAttribute() - : base("The number of records to skip before starting to fetch them. If this parameter is not provided, fetching starts from the beginning.") - { - } } + } - public class SwaggerTopParameterAttribute : SwaggerParameterAttribute + public class SwaggerTopParameterAttribute : SwaggerParameterAttribute + { + public SwaggerTopParameterAttribute() + : base("The maximum number of records to fetch. If this parameter is not provided, all records are fetched.") { - public SwaggerTopParameterAttribute() - : base("The maximum number of records to fetch. If this parameter is not provided, all records are fetched.") - { - } } + } } diff --git a/NorthwindCRUD/Constants/StringTemplates.cs b/NorthwindCRUD/Constants/StringTemplates.cs index a277f2a..36bd386 100644 --- a/NorthwindCRUD/Constants/StringTemplates.cs +++ b/NorthwindCRUD/Constants/StringTemplates.cs @@ -1,6 +1,4 @@ -using System.Xml.Linq; - -namespace NorthwindCRUD.Constants +namespace NorthwindCRUD.Constants { public class StringTemplates { diff --git a/NorthwindCRUD/Controllers/BaseController.cs b/NorthwindCRUD/Controllers/BaseController.cs index 10e6ca3..0ee6b89 100644 --- a/NorthwindCRUD/Controllers/BaseController.cs +++ b/NorthwindCRUD/Controllers/BaseController.cs @@ -1,5 +1,4 @@ using System.ComponentModel.DataAnnotations; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; @@ -7,32 +6,24 @@ namespace NorthwindCRUD.Controllers { - public class BaseController : ControllerBase + [ApiController] + [Route("[controller]")] + public class BaseNorthwindAPIController : ControllerBase where TDto : class, IBaseDto where TDb : class, IBaseDb, new() { - private readonly BaseDbService baseDbService; - private readonly ILogger logger; + protected readonly BaseDbService baseDbService; - public BaseController(BaseDbService baseDbService, ILogger logger) + public BaseNorthwindAPIController(BaseDbService baseDbService) { this.baseDbService = baseDbService; - this.logger = logger; } [HttpGet] public ActionResult GetAll() { - try - { - var result = this.baseDbService.GetAll(); - return Ok(result); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + var result = this.baseDbService.GetAll(); + return Ok(result); } /// @@ -48,17 +39,9 @@ public ActionResult> GetWithSkip( [FromQuery][Attributes.SwaggerTopParameter] int? top, [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) { - try - { - var pagedResult = this.baseDbService.GetWithPageSkip(skip, top, null, null, orderBy); + var pagedResult = this.baseDbService.GetWithPageSkip(skip, top, null, null, orderBy); - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + return Ok(pagedResult); } /// @@ -74,52 +57,60 @@ public ActionResult> GetWithPage( [FromQuery][Attributes.SwaggerSizeParameter] int? size, [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) { - try - { - var pagedResult = this.baseDbService.GetWithPageSkip(null, null, pageIndex, size, orderBy); + var pagedResult = this.baseDbService.GetWithPageSkip(null, null, pageIndex, size, orderBy); + return Ok(pagedResult); + } - return Ok(pagedResult); - } - catch (Exception error) + [HttpPost] + //[Authorize] + public async Task> Create(TDto model) + { + if (!ModelState.IsValid) { - logger.LogError(error.Message); - return StatusCode(500); + return BadRequest(ModelState); } + + var result = await this.baseDbService.Create(model); + return Ok(result); } - [HttpPost] + //[HttpPut("{id}")] + ////[Authorize] + //public async Task> Update(TDto model, TId id) + //{ + // if (!ModelState.IsValid) + // { + // return BadRequest(ModelState); + // } + + // var result = await this.baseDbService.Upsert(model, id); + // return Ok(result); + //} + [HttpPut] - [Authorize] - public async Task> UpsertAsync(TDto model) + //[Authorize] + public async Task> Update(TDto model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } - var result = await this.baseDbService.Upsert(model); + var result = await this.baseDbService.Update(model); return Ok(result); } [HttpGet("{id}")] public ActionResult GetById(TId id) { - try - { - var result = this.baseDbService.GetById(id); + var result = this.baseDbService.GetById(id); - if (result != null) - { - return result; - } - - return NotFound(); - } - catch (Exception error) + if (result != null) { - logger.LogError(error.Message); - return StatusCode(500); + return result; } + + return NotFound(); } /// @@ -131,5 +122,18 @@ public ActionResult GetCustomersCount() { return this.baseDbService.GetCount(); } + + [HttpDelete("{id}")] + //[Authorize] + public ActionResult Delete(TId id) + { + var product = this.baseDbService.Delete(id); + if (product != null) + { + return Ok(product); + } + + return NotFound(); + } } } diff --git a/NorthwindCRUD/Controllers/CategoriesController.cs b/NorthwindCRUD/Controllers/CategoriesController.cs index 3920ba4..69bb4d6 100644 --- a/NorthwindCRUD/Controllers/CategoriesController.cs +++ b/NorthwindCRUD/Controllers/CategoriesController.cs @@ -1,251 +1,45 @@ -//namespace NorthwindCRUD.Controllers -//{ -// using AutoMapper; -// using Microsoft.AspNetCore.Authorization; -// using Microsoft.AspNetCore.Mvc; -// using NorthwindCRUD.Models.DbModels; -// using NorthwindCRUD.Models.Dtos; -// using NorthwindCRUD.Services; -// using Swashbuckle.AspNetCore.Annotations; - -// [ApiController] -// [Route("[controller]")] -// public class CategoriesController : BaseController -// { -// private readonly CategoryService categoryService; -// private readonly ProductService productService; -// private readonly PagingService pagingService; -// private readonly IMapper mapper; -// private readonly ILogger logger; - -// public CategoriesController(CategoryService categoryService, ProductService productService, PagingService pagingService, IMapper mapper, ILogger logger) -// : base(categoryService, logger) -// { -// this.categoryService = categoryService; -// this.productService = productService; -// this.pagingService = pagingService; -// this.mapper = mapper; -// this.logger = logger; -// } - -// [HttpGet] -// public ActionResult GetAll() -// { -// try -// { -// var categories = this.categoryService.GetAll(); -// return Ok(this.mapper.Map(categories)); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// /// -// /// Fetches all categories or a page of categories based on the provided parameters. -// /// -// /// The number of records to skip before starting to fetch the categories. If this parameter is not provided, fetching starts from the beginning. -// /// The maximum number of categories to fetch. If this parameter is not provided, all categories are fetched. -// /// A comma-separated list of fields to order the categories by, along with the sort direction (e.g., "field1 asc, field2 desc"). -// /// A PagedResultDto object containing the fetched T and the total record count. -// [HttpGet("GetCategoriesWithSkip")] -// public ActionResult> GetCategoriesWithSkip( -// [FromQuery][Attributes.SwaggerSkipParameter] int? skip, -// [FromQuery][Attributes.SwaggerTopParameter] int? top, -// [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) -// { -// try -// { -// // Retrieve categories as Queryable -// var categories = this.categoryService.GetAllAsQueryable(); - -// // Get paged data -// var pagedResult = pagingService.FetchPagedData(categories, skip, top, null, null, orderBy); - -// return Ok(pagedResult); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// /// -// /// Fetches all categories or a page of categories based on the provided parameters. -// /// -// /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). -// /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. -// /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). -// /// A PagedResultDto object containing the fetched T and the total record count. -// [HttpGet("GetCategoriesWithPage")] -// public ActionResult> GetCategoriesWithPage( -// [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, -// [FromQuery][Attributes.SwaggerSizeParameter] int? size, -// [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) -// { -// try -// { -// // Retrieve categories as Queryable -// var categories = this.categoryService.GetAllAsQueryable(); - -// // Get paged data -// var pagedResult = pagingService.FetchPagedData(categories, null, null, pageIndex, size, orderBy); - -// return Ok(pagedResult); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// /// -// /// Retrieves the total number of categories. -// /// -// /// Total count of categories as an integer. -// [HttpGet("GetCategoriesCount")] -// public ActionResult GetCategoriesCount() -// { -// try -// { -// var count = categoryService.GetAllAsQueryable().Count(); -// return new CountResultDto() { Count = count }; -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// [HttpGet("{id}")] -// public ActionResult GetById(int id) -// { -// try -// { -// var category = this.categoryService.GetById(id); -// if (category != null) -// { -// return Ok(this.mapper.Map(category)); -// } - -// return NotFound(); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// [HttpGet("{id}/Details")] -// public ActionResult GetDetailsById(int id) -// { -// try -// { -// var category = this.categoryService.GetById(id); -// if (category != null) -// { -// return Ok(this.mapper.Map(category)); -// } - -// return NotFound(); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// [HttpGet("{id}/Products")] -// public ActionResult GetProductsByCategoryId(int id) -// { -// try -// { -// var products = this.productService.GetAllByCategoryId(id); -// return Ok(this.mapper.Map(products)); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// [HttpPost] -// [Authorize] -// public ActionResult Create(CategoryDto model) -// { -// try -// { -// if (ModelState.IsValid) -// { -// var mappedModel = this.mapper.Map(model); -// var category = this.categoryService.Create(mappedModel); -// return Ok(this.mapper.Map(category)); -// } - -// return BadRequest(ModelState); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// [HttpPut] -// [Authorize] -// public ActionResult Update(CategoryDto model) -// { -// try -// { -// if (ModelState.IsValid) -// { -// var mappedModel = this.mapper.Map(model); -// var category = this.categoryService.Update(mappedModel); - -// if (category != null) -// { -// return Ok(this.mapper.Map(category)); -// } - -// return NotFound(); -// } - -// return BadRequest(ModelState); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } - -// [HttpDelete("{id}")] -// [Authorize] -// public ActionResult Delete(int id) -// { -// try -// { -// var category = this.categoryService.Delete(id); -// if (category != null) -// { -// return Ok(this.mapper.Map(category)); -// } - -// return NotFound(); -// } -// catch (Exception error) -// { -// logger.LogError(error.Message); -// return StatusCode(500); -// } -// } -// } -//} \ No newline at end of file +namespace NorthwindCRUD.Controllers +{ + using AutoMapper; + using Microsoft.AspNetCore.Mvc; + using NorthwindCRUD.Models.DbModels; + using NorthwindCRUD.Models.Dtos; + using NorthwindCRUD.Services; + + [ApiController] + [Route("[controller]")] + public class CategoriesController : BaseNorthwindAPIController + { + private readonly CategoryService categoryService; + private readonly ProductService productService; + private readonly IMapper mapper; + private readonly ILogger logger; + + public CategoriesController(CategoryService categoryService, ProductService productService, IMapper mapper, ILogger logger) + : base(categoryService) + { + this.categoryService = categoryService; + this.productService = productService; + this.mapper = mapper; + } + + [HttpGet("{id}/Details")] + public ActionResult GetDetailsById(int id) + { + var category = this.categoryService.GetDetailsById(id); + if (category == null) + { + return NotFound(); + } + + return Ok(category); + } + + [HttpGet("{id}/Products")] + public ActionResult GetProductsByCategoryId(int id) + { + var products = this.productService.GetAllByCategoryId(id); + return Ok(products); + } + } +} \ No newline at end of file diff --git a/NorthwindCRUD/Controllers/CustomersController.cs b/NorthwindCRUD/Controllers/CustomersController.cs index f17f295..39d2156 100644 --- a/NorthwindCRUD/Controllers/CustomersController.cs +++ b/NorthwindCRUD/Controllers/CustomersController.cs @@ -8,12 +8,12 @@ [ApiController] [Route("[controller]")] - public class CustomersController : BaseController + public class CustomersController : BaseNorthwindAPIController { private readonly OrderService orderService; - public CustomersController(CustomerService customerService, OrderService orderService, PagingService pagingService, IMapper mapper, ILogger logger) - : base(customerService, logger) + public CustomersController(CustomerService customerService, OrderService orderService, IMapper mapper, ILogger logger) + : base(customerService) { this.orderService = orderService; } diff --git a/NorthwindCRUD/Controllers/EmployeesController.cs b/NorthwindCRUD/Controllers/EmployeesController.cs index dffab07..484015f 100644 --- a/NorthwindCRUD/Controllers/EmployeesController.cs +++ b/NorthwindCRUD/Controllers/EmployeesController.cs @@ -1,222 +1,70 @@ namespace NorthwindCRUD.Controllers { - using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; using NorthwindCRUD.Services; - using Swashbuckle.AspNetCore.Annotations; [ApiController] [Route("[controller]")] - public class EmployeesController : Controller + public class EmployeesController : BaseNorthwindAPIController { private readonly EmployeeService employeeService; - private readonly EmployeeTerritoryService employeeTerritoryService; private readonly OrderService ordersService; - private readonly PagingService pagingService; - private readonly IMapper mapper; + private readonly EmployeeTerritoryService employeeTerritoryService; private readonly ILogger logger; - public EmployeesController(EmployeeService employeeService, EmployeeTerritoryService employeeTerritoryService, OrderService ordersService, PagingService pagingService, IMapper mapper, ILogger logger) + public EmployeesController(EmployeeService employeeService, EmployeeTerritoryService employeeTerritoryService, OrderService ordersService, ILogger logger) + : base(employeeService) { this.employeeService = employeeService; this.employeeTerritoryService = employeeTerritoryService; - this.pagingService = pagingService; this.ordersService = ordersService; - this.mapper = mapper; this.logger = logger; } - [HttpGet] - public ActionResult GetAll() - { - try - { - var employees = this.employeeService.GetAll(); - return Ok(this.mapper.Map(employees)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all employees or a page of employees based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the employees. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of employees to fetch. If this parameter is not provided, all employees are fetched. - /// A comma-separated list of fields to order the employees by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetEmployeesWithSkip")] - public ActionResult> GetPagedEmployees( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve all employees as Queryable - var employees = this.employeeService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(employees, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all employees or a page of employees based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. - /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedEmployeesWithPage")] - public ActionResult> GetPagedEmployeesWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve employees as Queryable - var employees = this.employeeService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(employees, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Retrieves the total number of employees. - /// - /// Total count of employees as an integer. - [HttpGet("GetEmployeesCount")] - public ActionResult GetEmployeesCount() - { - try - { - var count = employeeService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}")] - public ActionResult GetById(int id) - { - try - { - var employee = this.employeeService.GetById(id); - - if (employee != null) - { - return Ok(this.mapper.Map(employee)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - [HttpGet("{id}/Superior")] public ActionResult GetSuperiorById(int id) { - try + var employee = this.baseDbService.GetById(id); + + if (employee != null) { - var employee = this.employeeService.GetById(id); + var superior = this.baseDbService.GetById(employee.ReportsTo); - if (employee != null) + if (superior != null) { - var superior = this.employeeService.GetById(employee.ReportsTo); - - if (superior != null) - { - return Ok(this.mapper.Map(superior)); - } + return Ok(superior); } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); } + + return NotFound(); } [HttpGet("{id}/Subordinates")] public ActionResult GetSubordinatesById(int id) { - try - { - return Ok(this.mapper.Map(this.employeeService.GetEmployeesByReportsTo(id))); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + return Ok(this.employeeService.GetEmployeesByReportsTo(id)); } [HttpGet("{id}/Orders")] public ActionResult GetOrdersByEmployeeId(int id) { - try - { - var orders = this.ordersService.GetOrdersByEmployeeId(id); - return Ok(this.mapper.Map(orders)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + var orders = this.ordersService.GetOrdersByEmployeeId(id); + return Ok(orders); } [HttpGet("{id}/Teritories")] public ActionResult GetTeritoriesByEmployeeId(int id) { - try + var teritories = this.employeeTerritoryService.GetTeritoriesByEmployeeId(id); + if (teritories == null) { - var teritories = this.employeeTerritoryService.GetTeritoriesByEmployeeId(id); - if (teritories == null) - { - return NotFound($"No territories for employee {id}"); - } - - return Ok(this.mapper.Map(teritories)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); + return NotFound($"No territories for employee {id}"); } + + return Ok(teritories); } [HttpPost("Teritory")] @@ -227,95 +75,17 @@ public ActionResult AddTerritoryToEmployee(EmployeeTerrito { if (ModelState.IsValid) { - var mappedModel = this.mapper.Map(model); - var employeeTerrirtory = this.employeeTerritoryService.AddTerritoryToEmployee(mappedModel); - return Ok(this.mapper.Map(employeeTerrirtory)); + var employeeTerrirtory = this.employeeTerritoryService.AddTerritoryToEmployee(model); + return Ok(employeeTerrirtory); } return BadRequest(ModelState); } catch (InvalidOperationException exception) { - logger.LogError(exception.Message); + this.logger.LogError(exception.Message); return StatusCode(400, exception.Message); } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPost] - [Authorize] - public ActionResult Create(EmployeeDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var employee = this.employeeService.Create(mappedModel); - return Ok(this.mapper.Map(employee)); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPut] - [Authorize] - public ActionResult Update(EmployeeDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var employee = this.employeeService.Update(mappedModel); - - if (employee != null) - { - return Ok(this.mapper.Map(employee)); - } - - return NotFound(); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpDelete("{id}")] - [Authorize] - public ActionResult Delete(int id) - { - try - { - var employee = this.employeeService.Delete(id); - - if (employee != null) - { - return Ok(this.mapper.Map(employee)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } } } } diff --git a/NorthwindCRUD/Controllers/OrdersController.cs b/NorthwindCRUD/Controllers/OrdersController.cs index afa30bd..d9db324 100644 --- a/NorthwindCRUD/Controllers/OrdersController.cs +++ b/NorthwindCRUD/Controllers/OrdersController.cs @@ -1,6 +1,5 @@ namespace NorthwindCRUD.Controllers { - using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; @@ -9,357 +8,110 @@ [ApiController] [Route("[controller]")] - public class OrdersController : ControllerBase + public class OrdersController : BaseNorthwindAPIController { private readonly OrderService orderService; private readonly EmployeeService employeeService; private readonly CustomerService customerService; private readonly ShipperService shipperService; private readonly ProductService productService; - private readonly PagingService pagingService; - private readonly IMapper mapper; - private readonly ILogger logger; - public OrdersController(OrderService orderService, EmployeeService employeeService, CustomerService customerService, ShipperService shipperService, ProductService productService, PagingService pagingService, IMapper mapper, ILogger logger) + public OrdersController(OrderService orderService, EmployeeService employeeService, CustomerService customerService, ShipperService shipperService, ProductService productService) + : base(orderService) { this.orderService = orderService; this.employeeService = employeeService; this.customerService = customerService; this.shipperService = shipperService; this.productService = productService; - this.pagingService = pagingService; - this.mapper = mapper; - this.logger = logger; - } - - [HttpGet] - public ActionResult GetAll() - { - try - { - var orders = this.orderService.GetAll(); - return Ok(this.mapper.Map(orders)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all orders or a page of orders based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the orders. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of orders to fetch. If this parameter is not provided, all orders are fetched. - /// A comma-separated list of fields to order the orders by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedOrders")] - public ActionResult> GetAllOrders( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve all orders - var orders = this.orderService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(orders, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all orders or a page of orders based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. - /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedOrdersWithPage")] - public ActionResult> GetPagedOrdersWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve orders as Queryable - var orders = this.orderService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(orders, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Retrieves the total number of orders. - /// - /// Total count of orders as an integer. - [HttpGet("GetOrdersCount")] - public ActionResult GetOrdersCount() - { - try - { - var count = orderService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}")] - public ActionResult GetById(int id) - { - try - { - var order = this.orderService.GetById(id); - - if (order != null) - { - return Ok(this.mapper.Map(order)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } } [HttpGet("{id}/Details")] public ActionResult GetDetailsByOrderId(int id) { - try + var orderDetail = this.orderService.GetOrderDetailsById(id); + if (orderDetail != null) { - var orderDetail = this.orderService.GetOrderDetailsById(id); - if (orderDetail != null) - { - return Ok(this.mapper.Map(orderDetail)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); + return Ok(orderDetail); } + + return NotFound(); } [HttpGet("{id}/Customer")] public ActionResult GetCustomerByOrderId(int id) { - try + var order = this.orderService.GetById(id); + if (order != null && order.CustomerId != null) { - var order = this.orderService.GetById(id); - if (order != null && order.CustomerId != null) - { - var customer = this.customerService.GetById(order.CustomerId); + var customer = this.customerService.GetById(order.CustomerId); - if (customer != null) - { - return customer; - } + if (customer != null) + { + return customer; } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); } + + return NotFound(); } [HttpGet("{id}/Employee")] public ActionResult GetEmployeeByOrderId(int id) { - try + var order = this.orderService.GetById(id); + if (order != null) { - var order = this.orderService.GetById(id); - if (order != null) + var employee = this.employeeService.GetById(order.EmployeeId); + if (employee != null) { - var employee = this.employeeService.GetById(order.EmployeeId ?? default); - if (employee != null) - { - return Ok(this.mapper.Map(employee)); - } + return Ok(employee); } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); } + + return NotFound(); } [HttpGet("{id}/Shipper")] public ActionResult GetShipperByOrderId(int id) { - try + var order = this.orderService.GetById(id); + if (order != null) { - var order = this.orderService.GetById(id); - if (order != null) - { - var shipper = this.shipperService.GetById(order.ShipVia); + var shipper = this.shipperService.GetById(order.ShipVia); - if (shipper != null) - { - return Ok(this.mapper.Map(shipper)); - } + if (shipper != null) + { + return Ok(shipper); } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); } + + return NotFound(); } [HttpGet("{id}/Products")] public ActionResult GetProductsByOrderId(int id) { - try - { - var orderDetails = this.orderService.GetOrderDetailsById(id); - if (orderDetails != null) - { - var productIds = orderDetails.Select(o => o.ProductId).ToArray(); - var products = this.productService.GetProductsByIds(productIds); - - if (products != null) - { - var productDtos = this.mapper.Map(products); - return Ok(productDtos); - } - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("retrieve/{ordersToRetrieve}")] - [Authorize] - public ActionResult OrdersToRetrieve(int ordersToRetrieve) - { - try - { - var orders = this.orderService.GetNOrders(ordersToRetrieve); - return Ok(this.mapper.Map(orders)); - } - catch (Exception error) + var orderDetails = this.orderService.GetOrderDetailsById(id); + if (orderDetails != null) { - logger.LogError(error.Message); - return StatusCode(500); - } - } + var productIds = orderDetails.Select(o => o.ProductId).ToArray(); + var products = this.productService.GetProductsByIds(productIds); - [HttpPost] - [Authorize] - public ActionResult Create(OrderDto model) - { - try - { - if (ModelState.IsValid) + if (products != null) { - var mappedModel = this.mapper.Map(model); - var order = this.orderService.Create(mappedModel); - return Ok(this.mapper.Map(order)); + return Ok(products); } - - return BadRequest(ModelState); - } - catch (InvalidOperationException exception) - { - return StatusCode(400, exception.Message); } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPut] - [Authorize] - public ActionResult Update(OrderDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var order = this.orderService.Update(mappedModel); - if (order != null) - { - return Ok(this.mapper.Map(order)); - } - - return NotFound(); - } - return BadRequest(ModelState); - } - catch (InvalidOperationException exception) - { - return StatusCode(400, exception.Message); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + return NotFound(); } - [HttpDelete("{id}")] + [HttpGet("retrieve/{ordersToRetrieve}")] [Authorize] - public ActionResult Delete(int id) + public ActionResult OrdersToRetrieve(int ordersToRetrieve) { - try - { - var order = this.orderService.Delete(id); - if (order != null) - { - return Ok(this.mapper.Map(order)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + var orders = this.orderService.GetNOrders(ordersToRetrieve); + return Ok(orders); } } } diff --git a/NorthwindCRUD/Controllers/ProductsController.cs b/NorthwindCRUD/Controllers/ProductsController.cs index 7301720..97927a2 100644 --- a/NorthwindCRUD/Controllers/ProductsController.cs +++ b/NorthwindCRUD/Controllers/ProductsController.cs @@ -1,300 +1,73 @@ namespace NorthwindCRUD.Controllers { - using System.Globalization; - using System.Reflection; - using AutoMapper; - using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; using NorthwindCRUD.Services; - using Swashbuckle.AspNetCore.Annotations; [ApiController] [Route("[controller]")] - public class ProductsController : ControllerBase + public class ProductsController : BaseNorthwindAPIController { private readonly ProductService productService; private readonly CategoryService categoryService; private readonly OrderService orderService; private readonly SupplierService supplierService; - private readonly PagingService pagingService; - private readonly IMapper mapper; - private readonly ILogger logger; - public ProductsController(ProductService productService, CategoryService categoryService, OrderService orderService, SupplierService supplierService, PagingService pagingService, IMapper mapper, ILogger logger) + public ProductsController(ProductService productService, CategoryService categoryService, OrderService orderService, SupplierService supplierService) + : base(productService) { this.productService = productService; this.categoryService = categoryService; this.orderService = orderService; this.supplierService = supplierService; - this.pagingService = pagingService; - this.mapper = mapper; - this.logger = logger; - } - - [HttpGet] - public ActionResult GetAll() - { - try - { - var products = this.productService.GetAll(); - return Ok(this.mapper.Map(products)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all products or a page of products based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the products. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of products to fetch. If this parameter is not provided, all products are fetched. - /// A comma-separated list of fields to order the products by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedProducts")] - public ActionResult> GetAllProducts( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve all products - var products = this.productService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(products, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all products or a page of products based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. - /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedProductsWithPage")] - public ActionResult> GetPagedProductsWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve products as Queryable - var products = this.productService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(products, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Retrieves the total number of products. - /// - /// Total count of products as an integer. - [HttpGet("GetProductsCount")] - public ActionResult GetProductsCount() - { - try - { - var count = productService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}")] - public ActionResult GetById(int id) - { - try - { - var product = this.productService.GetById(id); - if (product != null) - { - return Ok(this.mapper.Map(product)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } } [HttpGet("{id}/Category")] public ActionResult GetCategoryByProductId(int id) { - try + var product = this.productService.GetById(id); + if (product != null) { - var product = this.productService.GetById(id); - if (product != null) - { - var category = this.categoryService.GetById(product.CategoryId ?? default); + var category = this.categoryService.GetById(product.CategoryId ?? default); - if (category != null) - { - return Ok(this.mapper.Map(category)); - } + if (category != null) + { + return category; } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); } + + return NotFound(); } [HttpGet("{id}/OrderDetails")] public ActionResult GetOrderDetailsByProductId(int id) { - try - { - var product = this.productService.GetById(id); - if (product != null) - { - var orderDetails = this.orderService.GetOrderDetailsByProductId(id); - return Ok(this.mapper.Map(orderDetails)); - } - - return NotFound(); - } - catch (Exception error) + var product = this.productService.GetById(id); + if (product != null) { - logger.LogError(error.Message); - return StatusCode(500); + var orderDetails = this.orderService.GetOrderDetailsByProductId(id); + return Ok(orderDetails); } + + return NotFound(); } [HttpGet("{id}/Supplier")] public ActionResult GetSupplierByProductId(int id) { - try - { - var product = this.productService.GetById(id); - if (product != null) - { - var supplier = this.supplierService.GetById(product.SupplierId ?? default); - - if (supplier != null) - { - return Ok(this.mapper.Map(supplier)); - } - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPost] - [Authorize] - public ActionResult Create(ProductDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var product = this.productService.Create(mappedModel); - return Ok(this.mapper.Map(product)); - } - - return BadRequest(ModelState); - } - catch (InvalidOperationException exception) - { - return StatusCode(400, exception.Message); - } - catch (Exception error) + var product = this.productService.GetById(id); + if (product != null) { - logger.LogError(error.Message); - return StatusCode(500); - } - } + var supplier = this.supplierService.GetById(product.SupplierId ?? default); - [HttpPut] - [Authorize] - public ActionResult Update(ProductDto model) - { - try - { - if (ModelState.IsValid) + if (supplier != null) { - var mappedModel = this.mapper.Map(model); - var product = this.productService.Update(mappedModel); - - if (product != null) - { - return Ok(this.mapper.Map(product)); - } - - return NotFound(); + return Ok(supplier); } - - return BadRequest(ModelState); - } - catch (InvalidOperationException exception) - { - return StatusCode(400, exception.Message); } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - [HttpDelete("{id}")] - [Authorize] - public ActionResult Delete(int id) - { - try - { - var product = this.productService.Delete(id); - if (product != null) - { - return Ok(this.mapper.Map(product)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + return NotFound(); } } } \ No newline at end of file diff --git a/NorthwindCRUD/Controllers/RegionsController.cs b/NorthwindCRUD/Controllers/RegionsController.cs index 87afc3b..cb4e632 100644 --- a/NorthwindCRUD/Controllers/RegionsController.cs +++ b/NorthwindCRUD/Controllers/RegionsController.cs @@ -1,236 +1,34 @@ namespace NorthwindCRUD.Controllers { - using AutoMapper; - using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; - using NorthwindCRUD.Models.InputModels; using NorthwindCRUD.Services; - using Swashbuckle.AspNetCore.Annotations; [ApiController] [Route("[controller]")] - public class RegionsController : ControllerBase + public class RegionsController : BaseNorthwindAPIController { - private readonly RegionService regionService; private readonly TerritoryService territoryService; - private readonly PagingService pagingService; - private readonly IMapper mapper; - private readonly ILogger logger; - public RegionsController(RegionService regionService, TerritoryService territoryService, PagingService pagingService, IMapper mapper, ILogger logger) + public RegionsController(RegionService regionService, TerritoryService territoryService, OrderService ordersService) + : base(regionService) { - this.regionService = regionService; this.territoryService = territoryService; - this.pagingService = pagingService; - this.mapper = mapper; - this.logger = logger; - } - - [HttpGet] - public ActionResult GetAll() - { - try - { - var regions = this.regionService.GetAll(); - return Ok(this.mapper.Map(regions)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all regions or a page of regions based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the regions. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of regions to fetch. If this parameter is not provided, all regions are fetched. - /// A comma-separated list of fields to order the regions by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedRegions")] - public ActionResult> GetAllRegions( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve all regions - var regions = this.regionService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(regions, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all regions or a page of regions based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. - /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedRegionsWithPage")] - public ActionResult> GetPagedRegionsWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve regions as Queryable - var regions = this.regionService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(regions, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Retrieves the total number of regions. - /// - /// Total count of regions as an integer. - [HttpGet("GetRegionsCount")] - public ActionResult GetRegionsCount() - { - try - { - var count = regionService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}")] - public ActionResult GetById(int id) - { - try - { - var region = this.regionService.GetById(id); - if (region != null) - { - return Ok(this.mapper.Map(region)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } } [HttpGet("{id}/Territories")] public ActionResult GetTerritoryByRegionId(int id) { - try - { - var region = this.regionService.GetById(id); - if (region != null) - { - var territories = this.territoryService.GetTerritoriesByRegionId(id); - return Ok(this.mapper.Map(territories)); - } - return NotFound(); - } - catch (Exception error) + var region = this.baseDbService.GetById(id); + if (region != null) { - logger.LogError(error.Message); - return StatusCode(500); + var territories = this.territoryService.GetTerritoriesByRegionId(id); + return Ok(territories); } - } - - [HttpPost] - public ActionResult Create(RegionDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var region = this.regionService.Create(mappedModel); - return Ok(this.mapper.Map(region)); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - [HttpPut] - [Authorize] - public ActionResult Update(RegionDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var region = this.regionService.Update(mappedModel); - - if (region != null) - { - return Ok(this.mapper.Map(region)); - } - - return NotFound(); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpDelete("{id}")] - [Authorize] - public ActionResult Delete(int id) - { - try - { - var region = this.regionService.Delete(id); - if (region != null) - { - return Ok(this.mapper.Map(region)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + return NotFound(); } } } \ No newline at end of file diff --git a/NorthwindCRUD/Controllers/SalesController.cs b/NorthwindCRUD/Controllers/SalesController.cs index 6069203..5164432 100644 --- a/NorthwindCRUD/Controllers/SalesController.cs +++ b/NorthwindCRUD/Controllers/SalesController.cs @@ -25,7 +25,7 @@ public SalesController(SalesService salesService, IMapper mapper, ILogger GetSalesByCategoryAndYear([FromQuery] [Required] string categoryName, [FromQuery] int? orderYear = null) + public ActionResult GetSalesByCategoryAndYear([FromQuery][Required] string categoryName, [FromQuery] int? orderYear = null) { try { @@ -42,8 +42,8 @@ public ActionResult GetSalesByCategoryAndYear([FromQuery] [Required] [Authorize] public ActionResult GetSalesByCountry( string country, - [FromQuery] [Required] [DataType(DataType.Date)] [SwaggerParameter("Start date in YYYY-MM-DD format")] string startDate, - [FromQuery] [Required] [DataType(DataType.Date)] [SwaggerParameter("End date in YYYY-MM-DD format")] string endDate) + [FromQuery][Required][DataType(DataType.Date)][SwaggerParameter("Start date in YYYY-MM-DD format")] string startDate, + [FromQuery][Required][DataType(DataType.Date)][SwaggerParameter("End date in YYYY-MM-DD format")] string endDate) { try { diff --git a/NorthwindCRUD/Controllers/ShippersController.cs b/NorthwindCRUD/Controllers/ShippersController.cs index cb3395f..0fdf38b 100644 --- a/NorthwindCRUD/Controllers/ShippersController.cs +++ b/NorthwindCRUD/Controllers/ShippersController.cs @@ -1,231 +1,26 @@ namespace NorthwindCRUD.Controllers { - using AutoMapper; - using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; - using NorthwindCRUD.Models.InputModels; using NorthwindCRUD.Services; - using Swashbuckle.AspNetCore.Annotations; [ApiController] [Route("[controller]")] - public class ShippersController : ControllerBase + public class ShippersController : BaseNorthwindAPIController { - private readonly ShipperService shipperService; private readonly OrderService orderService; - private readonly PagingService pagingService; - private readonly IMapper mapper; - private readonly ILogger logger; - public ShippersController(ShipperService shipperService, OrderService orderService, PagingService pagingService, IMapper mapper, ILogger logger) + public ShippersController(ShipperService shipperService, OrderService orderService) + : base(shipperService) { - this.shipperService = shipperService; - this.orderService = orderService; - this.pagingService = pagingService; - this.mapper = mapper; - this.logger = logger; - } - - [HttpGet] - public ActionResult GetAll() - { - try - { - var shippers = this.shipperService.GetAll(); - return Ok(this.mapper.Map(shippers)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all shippers or a page of shippers based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the shippers. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of shippers to fetch. If this parameter is not provided, all shippers are fetched. - /// A comma-separated list of fields to order the shippers by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedShippersWithSkip")] - public ActionResult> GetPagedShippersWithSkip( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve all shippers - var shippers = this.shipperService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(shippers, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all shippers or a page of shippers based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. - /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedShippersWithPage")] - public ActionResult> GetPagedShippersWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve shippers as Queryable - var shippers = this.shipperService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(shippers, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Retrieves the total number of shippers. - /// - /// Total count of shippers as an integer. - [HttpGet("GetShippersCount")] - public ActionResult GetShippersCount() - { - try - { - var count = shipperService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}")] - public ActionResult GetById(int id) - { - try - { - var category = this.shipperService.GetById(id); - if (category != null) - { - return Ok(this.mapper.Map(category)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } } [HttpGet("{id}/Orders")] public ActionResult GetOrdersByShipperId(int id) { - try - { - var orders = this.orderService.GetOrdersByShipperId(id); - return Ok(this.mapper.Map(orders)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPost] - [Authorize] - public ActionResult Create(ShipperDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var shipper = this.shipperService.Create(mappedModel); - return Ok(this.mapper.Map(shipper)); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPut] - [Authorize] - public ActionResult Update(ShipperDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var shipper = this.shipperService.Update(mappedModel); - - if (shipper != null) - { - return Ok(this.mapper.Map(shipper)); - } - - return NotFound(); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpDelete("{id}")] - [Authorize] - public ActionResult Delete(int id) - { - try - { - var shipper = this.shipperService.Delete(id); - if (shipper != null) - { - return Ok(this.mapper.Map(shipper)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + var orders = this.orderService.GetOrdersByShipperId(id); + return Ok(orders); } } } \ No newline at end of file diff --git a/NorthwindCRUD/Controllers/SuppliersController.cs b/NorthwindCRUD/Controllers/SuppliersController.cs index 4d9f0ca..46b809a 100644 --- a/NorthwindCRUD/Controllers/SuppliersController.cs +++ b/NorthwindCRUD/Controllers/SuppliersController.cs @@ -1,231 +1,28 @@ namespace NorthwindCRUD.Controllers { using AutoMapper; - using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; - using NorthwindCRUD.Models.InputModels; using NorthwindCRUD.Services; - using Swashbuckle.AspNetCore.Annotations; [ApiController] [Route("[controller]")] - public class SuppliersController : ControllerBase + public class SuppliersController : BaseNorthwindAPIController { - private readonly SupplierService supplierService; private readonly ProductService productService; - private readonly PagingService pagingService; - private readonly IMapper mapper; - private readonly ILogger logger; - public SuppliersController(SupplierService supplierService, ProductService productService, PagingService pagingService, IMapper mapper, ILogger logger) + public SuppliersController(SupplierService supplierService, ProductService productService, IMapper mapper, ILogger logger) + : base(supplierService) { - this.supplierService = supplierService; this.productService = productService; - this.pagingService = pagingService; - this.mapper = mapper; - this.logger = logger; - } - - [HttpGet] - public ActionResult GetAll() - { - try - { - var suppliers = this.supplierService.GetAll(); - return Ok(this.mapper.Map(suppliers)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all suppliers or a page of suppliers based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the suppliers. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of suppliers to fetch. If this parameter is not provided, all suppliers are fetched. - /// A comma-separated list of fields to order the suppliers by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedSuppliers")] - public ActionResult> GetAllSuppliers( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve all suppliers - var suppliers = this.supplierService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(suppliers, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all suppliers or a page of suppliers based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all records are fetched. - /// A comma-separated list of fields to order the records by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedSuppliersWithPage")] - public ActionResult> GetPagedSuppliersWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve suppliers as Queryable - var suppliers = this.supplierService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(suppliers, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Retrieves the total number of suppliers. - /// - /// Total count of suppliers as an integer. - [HttpGet("GetSuppliersCount")] - public ActionResult GetSuppliersCount() - { - try - { - var count = supplierService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpGet("{id}")] - public ActionResult GetById(int id) - { - try - { - var supplier = this.supplierService.GetById(id); - if (supplier != null) - { - return Ok(this.mapper.Map(supplier)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } } [HttpGet("{id}/Products")] public ActionResult GetProductsBySupplierId(int id) { - try - { - var products = this.productService.GetAllBySupplierId(id); - return Ok(this.mapper.Map(products)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPost] - [Authorize] - public ActionResult Create(SupplierDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var supplier = this.supplierService.Create(mappedModel); - return Ok(this.mapper.Map(supplier)); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpPut] - [Authorize] - public ActionResult Update(SupplierDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var supplier = this.supplierService.Update(mappedModel); - - if (supplier != null) - { - return Ok(this.mapper.Map(supplier)); - } - - return NotFound(); - } - - return BadRequest(ModelState); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpDelete("{id}")] - [Authorize] - public ActionResult Delete(int id) - { - try - { - var supplier = this.supplierService.Delete(id); - if (supplier != null) - { - return Ok(this.mapper.Map(supplier)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + var products = this.productService.GetAllBySupplierId(id); + return Ok(products); } } } \ No newline at end of file diff --git a/NorthwindCRUD/Controllers/TerritoriesController.cs b/NorthwindCRUD/Controllers/TerritoriesController.cs index 0025dcb..4deddb6 100644 --- a/NorthwindCRUD/Controllers/TerritoriesController.cs +++ b/NorthwindCRUD/Controllers/TerritoriesController.cs @@ -1,271 +1,65 @@ namespace NorthwindCRUD.Controllers { - using AutoMapper; - using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; - using NorthwindCRUD.Models.InputModels; using NorthwindCRUD.Services; - using Swashbuckle.AspNetCore.Annotations; [ApiController] [Route("[controller]")] - public class TerritoriesController : ControllerBase + public class TerritoriesController : BaseNorthwindAPIController { - private readonly TerritoryService territoryService; private readonly RegionService regionService; private readonly EmployeeTerritoryService employeeTerritoryService; - private readonly PagingService pagingService; - private readonly IMapper mapper; - private readonly ILogger logger; - public TerritoriesController(TerritoryService territoryService, EmployeeTerritoryService employeeTerritoryService, RegionService regionService, PagingService pagingService, IMapper mapper, ILogger logger) + public TerritoriesController(TerritoryService territoryService, RegionService regionService, EmployeeTerritoryService employeeTerritoryService) + : base(territoryService) { - this.territoryService = territoryService; this.regionService = regionService; this.employeeTerritoryService = employeeTerritoryService; - this.pagingService = pagingService; - this.mapper = mapper; - this.logger = logger; } - [HttpGet] - public ActionResult GetAll() - { - try - { - var territories = this.territoryService.GetAll(); - return Ok(this.mapper.Map(territories)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all territories or a page of territories based on the provided parameters. - /// - /// The number of records to skip before starting to fetch the territories. If this parameter is not provided, fetching starts from the beginning. - /// The maximum number of territories to fetch. If this parameter is not provided, all territories are fetched. - /// A comma-separated list of fields to order the territories by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedTerritories")] - public ActionResult> GetAllTerritories( - [FromQuery][Attributes.SwaggerSkipParameter] int? skip, - [FromQuery][Attributes.SwaggerTopParameter] int? top, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve all territories - var territories = this.territoryService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(territories, skip, top, null, null, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - /// - /// Fetches all territories or a page of territories based on the provided parameters. - /// - /// The page index of records to fetch. If this parameter is not provided, fetching starts from the beginning (page 0). - /// The maximum number of records to fetch per page. If this parameter is not provided, all territories are fetched. - /// A comma-separated list of fields to order the territories by, along with the sort direction (e.g., "field1 asc, field2 desc"). - /// A PagedResultDto object containing the fetched T and the total record count. - [HttpGet("GetPagedTerritoriesWithPage")] - public ActionResult> GetPagedTerritoriesWithPage( - [FromQuery][Attributes.SwaggerPageParameter] int? pageIndex, - [FromQuery][Attributes.SwaggerSizeParameter] int? size, - [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) - { - try - { - // Retrieve territories as Queryable - var territories = this.territoryService.GetAllAsQueryable(); - - // Get paged data - var pagedResult = pagingService.FetchPagedData(territories, null, null, pageIndex, size, orderBy); - - return Ok(pagedResult); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - /// - /// Retrieves the total number of territories. - /// - /// Total count of territories as an integer. - [HttpGet("GetTerritoriesCount")] - public ActionResult GetTerritoriesCount() - { - try - { - var count = territoryService.GetAllAsQueryable().Count(); - return new CountResultDto() { Count = count }; - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } + //[HttpPost] + ////[Authorize] + //public override async Task> CreateAsync(TerritoryDto model) + //{ + // if (!ModelState.IsValid) + // { + // return BadRequest(ModelState); + // } - [HttpGet("{id}")] - public ActionResult GetById(string id) - { - try - { - var teritory = this.territoryService.GetById(id); - if (teritory != null) - { - return Ok(this.mapper.Map(teritory)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } + // var result = await this.baseDbService.Upsert(model, default); + // return Ok(result); + //} [HttpGet("{id}/Employees")] public ActionResult GetEmployeesByTerritory(string id) { - try + var employees = this.employeeTerritoryService.GetEmployeesByTerritoryId(id); + if (employees == null) { - var employees = this.employeeTerritoryService.GetEmployeesByTerritoryId(id); - if (employees == null) - { - return NotFound($"No employees for territory {id}"); - } - - return Ok(this.mapper.Map(employees)); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); + return NotFound($"No employees for territory {id}"); } + + return Ok(employees); } [HttpGet("{id}/Region")] public ActionResult GetRegionByTerritory(string id) { - try + var territory = this.baseDbService.GetById(id); + if (territory != null) { - var territory = this.territoryService.GetById(id); - if (territory != null) - { - var region = this.regionService.GetById(territory.RegionId ?? default); - - if (region != null) - { - return Ok(this.mapper.Map(region)); - } - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } + var region = this.regionService.GetById(territory.RegionId ?? default); - [HttpPost] - [Authorize] - public ActionResult Create(TerritoryDto model) - { - try - { - if (ModelState.IsValid) + if (region != null) { - var mappedModel = this.mapper.Map(model); - var teritory = this.territoryService.Create(mappedModel); - return Ok(this.mapper.Map(teritory)); + return Ok(region); } - - return BadRequest(ModelState); - } - catch (InvalidOperationException exception) - { - return StatusCode(400, exception.Message); } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - [HttpPut] - [Authorize] - public ActionResult Update(TerritoryDto model) - { - try - { - if (ModelState.IsValid) - { - var mappedModel = this.mapper.Map(model); - var territory = this.territoryService.Update(mappedModel); - - if (territory != null) - { - return Ok(this.mapper.Map(territory)); - } - - return NotFound(); - } - - return BadRequest(ModelState); - } - catch (InvalidOperationException exception) - { - return StatusCode(400, exception.Message); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } - } - - [HttpDelete("{id}")] - [Authorize] - public ActionResult Delete(string id) - { - try - { - var territory = this.territoryService.Delete(id); - if (territory != null) - { - return Ok(this.mapper.Map(territory)); - } - - return NotFound(); - } - catch (Exception error) - { - logger.LogError(error.Message); - return StatusCode(500); - } + return NotFound(); } } } \ No newline at end of file diff --git a/NorthwindCRUD/ControllersGraphQL/CategoryController.cs b/NorthwindCRUD/ControllersGraphQL/CategoryController.cs index c5ba167..2444544 100644 --- a/NorthwindCRUD/ControllersGraphQL/CategoryController.cs +++ b/NorthwindCRUD/ControllersGraphQL/CategoryController.cs @@ -1,9 +1,9 @@ namespace NorthwindCRUD.Controllers { + using System.Threading.Tasks; using AutoMapper; using GraphQL.AspNet.Attributes; using GraphQL.AspNet.Controllers; - using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; using NorthwindCRUD.Services; @@ -11,21 +11,17 @@ namespace NorthwindCRUD.Controllers public class CategoryGraphController : GraphController { private readonly CategoryService categoryService; - private readonly IMapper mapper; - private readonly ILogger logger; public CategoryGraphController(CategoryService categoryService, IMapper mapper, ILogger logger) { this.categoryService = categoryService; - this.mapper = mapper; - this.logger = logger; } [Query] public CategoryDto[] GetAll() { var categories = this.categoryService.GetAll(); - return this.mapper.Map(categories); + return categories; } [Query] @@ -35,40 +31,31 @@ public CategoryDto[] GetAll() if (category != null) { - return this.mapper.Map(category); + return category; } return null; } [Mutation] - public CategoryDto Create(CategoryDto model) + public async Task Create(CategoryDto model) { - var mappedModel = this.mapper.Map(model); - var category = this.categoryService.Create(mappedModel); - return this.mapper.Map(category); + var category = await this.categoryService.Create(model); + return category; } [Mutation] - public CategoryDto? Update(CategoryDto model) + public async Task Update(CategoryDto model) { - var mappedModel = this.mapper.Map(model); - var category = this.categoryService.Update(mappedModel); - - return category != null ? this.mapper.Map(category) : null; + var category = await this.categoryService.Update(model); + return category; } [Mutation] public CategoryDto? Delete(int id) { var category = this.categoryService.Delete(id); - - if (category != null) - { - return this.mapper.Map(category); - } - - return null; + return category; } } } \ No newline at end of file diff --git a/NorthwindCRUD/ControllersGraphQL/CustomerController.cs b/NorthwindCRUD/ControllersGraphQL/CustomerController.cs index b723a0e..6032bcd 100644 --- a/NorthwindCRUD/ControllersGraphQL/CustomerController.cs +++ b/NorthwindCRUD/ControllersGraphQL/CustomerController.cs @@ -1,5 +1,4 @@ -using AutoMapper; -using GraphQL.AspNet.Attributes; +using GraphQL.AspNet.Attributes; using GraphQL.AspNet.Controllers; using NorthwindCRUD.Models.Dtos; using NorthwindCRUD.Services; @@ -11,7 +10,7 @@ public class CustomerGraphController : GraphController { private readonly CustomerService customerService; - public CustomerGraphController(CustomerService customerService, IMapper mapper, ILogger logger) + public CustomerGraphController(CustomerService customerService) { this.customerService = customerService; } @@ -33,13 +32,13 @@ public CustomerDto[] GetAll() [Mutation] public async Task Create(CustomerDto model) { - return await this.customerService.Upsert(model); + return await this.customerService.Create(model); } [Mutation] - public async Task UpdateAsync(CustomerDto model) + public async Task Update(CustomerDto model) { - return await this.customerService.Upsert(model); + return await this.customerService.Update(model); } [Mutation] diff --git a/NorthwindCRUD/ControllersGraphQL/EmployeeController.cs b/NorthwindCRUD/ControllersGraphQL/EmployeeController.cs index f9cead2..76d9ed7 100644 --- a/NorthwindCRUD/ControllersGraphQL/EmployeeController.cs +++ b/NorthwindCRUD/ControllersGraphQL/EmployeeController.cs @@ -1,32 +1,26 @@ namespace NorthwindCRUD.Controllers { - using AutoMapper; + using System.Threading.Tasks; using GraphQL.AspNet.Attributes; using GraphQL.AspNet.Controllers; - using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; - using NorthwindCRUD.Models.InputModels; using NorthwindCRUD.Services; [GraphRoute("employee")] public class EmployeeGraphController : GraphController { private readonly EmployeeService employeeService; - private readonly IMapper mapper; - private readonly ILogger logger; - public EmployeeGraphController(EmployeeService employeeService, IMapper mapper, ILogger logger) + public EmployeeGraphController(EmployeeService employeeService) { this.employeeService = employeeService; - this.mapper = mapper; - this.logger = logger; } [Query] public EmployeeDto[] GetAll() { var employees = this.employeeService.GetAll(); - return this.mapper.Map(employees); + return employees; } [Query] @@ -34,28 +28,21 @@ public EmployeeDto[] GetAll() { var employee = this.employeeService.GetById(id); - if (employee != null) - { - return this.mapper.Map(employee); - } - - return null; + return employee; } [Mutation] - public EmployeeDto Create(EmployeeDto model) + public async Task Create(EmployeeDto model) { - var mappedModel = this.mapper.Map(model); - var employee = this.employeeService.Create(mappedModel); - return this.mapper.Map(employee); + var employee = await this.employeeService.Create(model); + return employee; } [Mutation] - public EmployeeDto? Update(EmployeeDto model) + public async Task Update(EmployeeDto model) { - var mappedModel = this.mapper.Map(model); - var employee = this.employeeService.Update(mappedModel); - return employee != null ? this.mapper.Map(employee) : null; + var employee = await this.employeeService.Update(model); + return employee; } [Mutation] @@ -63,12 +50,7 @@ public EmployeeDto Create(EmployeeDto model) { var employee = this.employeeService.Delete(id); - if (employee != null) - { - return this.mapper.Map(employee); - } - - return null; + return employee; } } } diff --git a/NorthwindCRUD/ControllersGraphQL/OrderController.cs b/NorthwindCRUD/ControllersGraphQL/OrderController.cs index 06eda20..dacfd10 100644 --- a/NorthwindCRUD/ControllersGraphQL/OrderController.cs +++ b/NorthwindCRUD/ControllersGraphQL/OrderController.cs @@ -1,7 +1,5 @@ -using AutoMapper; -using GraphQL.AspNet.Attributes; +using GraphQL.AspNet.Attributes; using GraphQL.AspNet.Controllers; -using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; using NorthwindCRUD.Services; @@ -11,21 +9,17 @@ namespace NorthwindCRUD.Controllers public class OrderGraphController : GraphController { private readonly OrderService orderService; - private readonly IMapper mapper; - private readonly ILogger logger; - public OrderGraphController(OrderService orderService, IMapper mapper, ILogger logger) + public OrderGraphController(OrderService orderService) { this.orderService = orderService; - this.mapper = mapper; - this.logger = logger; } [Query] public OrderDto[] GetAll() { var orders = this.orderService.GetAll(); - return this.mapper.Map(orders); + return orders; } [Query] @@ -35,39 +29,31 @@ public OrderDto[] GetAll() if (order != null) { - return this.mapper.Map(order); + return order; } return null; } [Mutation] - public OrderDto Create(OrderDto model) + public async Task Create(OrderDto model) { - var mappedModel = this.mapper.Map(model); - var order = this.orderService.Create(mappedModel); - return this.mapper.Map(order); + var order = await this.orderService.Create(model); + return order; } [Mutation] - public OrderDto? Update(OrderDto model) + public async Task Update(OrderDto model) { - var mappedModel = this.mapper.Map(model); - var order = this.orderService.Update(mappedModel); - return order != null ? this.mapper.Map(order) : null; + var order = await orderService.Update(model, model.OrderId); + return order; } [Mutation] public OrderDto? Delete(int id) { var order = this.orderService.Delete(id); - - if (order != null) - { - return this.mapper.Map(order); - } - - return null; + return order; } } } diff --git a/NorthwindCRUD/DataContext.cs b/NorthwindCRUD/DataContext.cs index 72ab415..08fd210 100644 --- a/NorthwindCRUD/DataContext.cs +++ b/NorthwindCRUD/DataContext.cs @@ -10,7 +10,7 @@ public DataContext(DbContextOptions options) { } - public DbSet Addresses { get; set; } + //public DbSet Addresses { get; set; } public DbSet Categories { get; set; } @@ -38,10 +38,6 @@ public DataContext(DbContextOptions options) protected override void OnModelCreating(ModelBuilder modelBuilder) { - modelBuilder.Entity() - .Property(a => a.AddressId) - .ValueGeneratedOnAdd(); - modelBuilder.Entity() .HasOne(p => p.Category) .WithMany(c => c.Products) @@ -53,14 +49,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .OnDelete(DeleteBehavior.SetNull); modelBuilder.Entity() - .HasOne(c => c.Address) - .WithMany(a => a.Customers) - .OnDelete(DeleteBehavior.NoAction); + .OwnsOne(c => c.Address); modelBuilder.Entity() - .HasOne(o => o.ShipAddress) - .WithMany(a => a.Orders) - .OnDelete(DeleteBehavior.SetNull); + .OwnsOne(o => o.ShipAddress); modelBuilder.Entity() .HasOne(o => o.Customer) @@ -80,9 +72,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .OnDelete(DeleteBehavior.SetNull); modelBuilder.Entity() - .HasOne(e => e.Address) - .WithMany(a => a.Employees) - .OnDelete(DeleteBehavior.NoAction); + .OwnsOne(e => e.Address); modelBuilder.Entity() .HasOne(t => t.Region) @@ -97,12 +87,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasOne(et => et.Territory) .WithMany(t => t.EmployeesTerritories); - //Composite Keys modelBuilder.Entity() .HasKey(et => new { et.EmployeeId, et.TerritoryId }); modelBuilder.Entity() .HasKey(et => new { et.ProductId, et.OrderId }); } + } } diff --git a/NorthwindCRUD/Helpers/DBSeeder.cs b/NorthwindCRUD/Helpers/DBSeeder.cs index 435aac1..2bbad90 100644 --- a/NorthwindCRUD/Helpers/DBSeeder.cs +++ b/NorthwindCRUD/Helpers/DBSeeder.cs @@ -121,10 +121,10 @@ private static void SeedOrders(DataContext dbContext) { if (order.ShipAddress != null) { - if (dbContext.Addresses.FirstOrDefault(a => a.Street == order.ShipAddress.Street) == null) - { - dbContext.Addresses.Add(order.ShipAddress); - } + //if (dbContext.Addresses.FirstOrDefault(a => a.Street == order.ShipAddress.Street) == null) + //{ + // dbContext.Addresses.Add(order.ShipAddress); + //} dbContext.Orders.Add(order); } @@ -159,10 +159,10 @@ private static void SeedEmployees(DataContext dbContext) { foreach (var employee in parsedEmployees) { - if (dbContext.Addresses.FirstOrDefault(a => a.Street == employee.Address.Street) == null) - { - dbContext.Addresses.Add(employee.Address); - } + //if (dbContext.Addresses.FirstOrDefault(a => a.Street == employee.Address.Street) == null) + //{ + // dbContext.Addresses.Add(employee.Address); + //} dbContext.Employees.Add(employee); } @@ -187,10 +187,10 @@ private static void SeedCustomers(DataContext dbContext) if (existingCustomer == null) { - if (dbContext.Addresses.FirstOrDefault(a => a.Street == customer.Address.Street) == null) - { - dbContext.Addresses.Add(customer.Address); - } + //if (dbContext.Addresses.FirstOrDefault(a => a.Street == customer.Address.Street) == null) + //{ + // dbContext.Addresses.Add(customer.Address); + //} dbContext.Customers.Add(customer); } diff --git a/NorthwindCRUD/Helpers/MappingProfiles.cs b/NorthwindCRUD/Helpers/MappingProfiles.cs index 675a14c..f6fc12e 100644 --- a/NorthwindCRUD/Helpers/MappingProfiles.cs +++ b/NorthwindCRUD/Helpers/MappingProfiles.cs @@ -1,29 +1,63 @@ -namespace NorthwindCRUD.Helpers -{ - using AutoMapper; - using NorthwindCRUD.Models.DbModels; - using NorthwindCRUD.Models.Dtos; +using AutoMapper; +using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; - public class MappingProfiles : Profile +public class MappingProfiles : Profile +{ + public MappingProfiles() { - public MappingProfiles() - { - CreateMap().ReverseMap(); - CreateMap(); - - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - } + // Entity to Entity (Ignoring ID fields) + CreateMap() + .ForMember(dest => dest.CategoryId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.CustomerId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.SupplierId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.EmployeeId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.TerritoryId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.RegionId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.OrderId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.ProductId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.ShipperId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + // DTO to DB and Reverse mappings + CreateMap().ReverseMap(); + CreateMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); } } diff --git a/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.Designer.cs b/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.Designer.cs new file mode 100644 index 0000000..cf8fdab --- /dev/null +++ b/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.Designer.cs @@ -0,0 +1,610 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NorthwindCRUD; + +#nullable disable + +namespace NorthwindCRUD.Migrations +{ + [DbContext(typeof(DataContext))] + [Migration("20241022072605_TablesToOwnAddress")] + partial class TablesToOwnAddress + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "6.0.22"); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CategoryDb", b => + { + b.Property("CategoryId") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Description") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Picture") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("CategoryId"); + + b.ToTable("Categories"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CustomerDb", b => + { + b.Property("CustomerId") + .HasColumnType("TEXT"); + + b.Property("CompanyName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ContactName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ContactTitle") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("CustomerId"); + + b.ToTable("Customers"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeDb", b => + { + b.Property("EmployeeId") + .HasColumnType("INTEGER"); + + b.Property("AvatarUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("BirthDate") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("HireDate") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Notes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReportsTo") + .HasColumnType("INTEGER"); + + b.Property("Title") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TitleOfCourtesy") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("EmployeeId"); + + b.ToTable("Employees"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeTerritoryDb", b => + { + b.Property("EmployeeId") + .HasColumnType("INTEGER"); + + b.Property("TerritoryId") + .HasColumnType("TEXT"); + + b.HasKey("EmployeeId", "TerritoryId"); + + b.HasIndex("TerritoryId"); + + b.ToTable("EmployeesTerritories"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.OrderDb", b => + { + b.Property("OrderId") + .HasColumnType("INTEGER"); + + b.Property("CustomerId") + .HasColumnType("TEXT"); + + b.Property("Discount") + .HasColumnType("REAL"); + + b.Property("EmployeeId") + .HasColumnType("INTEGER"); + + b.Property("Freight") + .HasColumnType("REAL"); + + b.Property("OrderDate") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Quantity") + .HasColumnType("INTEGER"); + + b.Property("RequiredDate") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ShipName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ShipVia") + .HasColumnType("INTEGER"); + + b.Property("ShipperId") + .HasColumnType("INTEGER"); + + b.Property("UnitPrice") + .HasColumnType("REAL"); + + b.HasKey("OrderId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("EmployeeId"); + + b.HasIndex("ShipperId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.OrderDetailDb", b => + { + b.Property("ProductId") + .HasColumnType("INTEGER"); + + b.Property("OrderId") + .HasColumnType("INTEGER"); + + b.Property("Discount") + .HasColumnType("REAL"); + + b.Property("Quantity") + .HasColumnType("INTEGER"); + + b.Property("UnitPrice") + .HasColumnType("REAL"); + + b.HasKey("ProductId", "OrderId"); + + b.HasIndex("OrderId"); + + b.ToTable("OrderDetails"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ProductDb", b => + { + b.Property("ProductId") + .HasColumnType("INTEGER"); + + b.Property("CategoryId") + .HasColumnType("INTEGER"); + + b.Property("Discontinued") + .HasColumnType("INTEGER"); + + b.Property("QuantityPerUnit") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReorderLevel") + .HasColumnType("INTEGER"); + + b.Property("SupplierId") + .HasColumnType("INTEGER"); + + b.Property("UnitPrice") + .HasColumnType("REAL"); + + b.Property("UnitsInStock") + .HasColumnType("INTEGER"); + + b.Property("UnitsOnOrder") + .HasColumnType("INTEGER"); + + b.HasKey("ProductId"); + + b.HasIndex("CategoryId"); + + b.HasIndex("SupplierId"); + + b.ToTable("Products"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.RegionDb", b => + { + b.Property("RegionId") + .HasColumnType("INTEGER"); + + b.Property("RegionDescription") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("RegionId"); + + b.ToTable("Regions"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ShipperDb", b => + { + b.Property("ShipperId") + .HasColumnType("INTEGER"); + + b.Property("CompanyName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Phone") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("ShipperId"); + + b.ToTable("Shippers"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.SupplierDb", b => + { + b.Property("SupplierId") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Address") + .HasColumnType("TEXT"); + + b.Property("City") + .HasColumnType("TEXT"); + + b.Property("CompanyName") + .HasColumnType("TEXT"); + + b.Property("ContactName") + .HasColumnType("TEXT"); + + b.Property("ContactTitle") + .HasColumnType("TEXT"); + + b.Property("Country") + .HasColumnType("TEXT"); + + b.Property("Fax") + .HasColumnType("TEXT"); + + b.Property("HomePage") + .HasColumnType("TEXT"); + + b.Property("Phone") + .HasColumnType("TEXT"); + + b.Property("PostalCode") + .HasColumnType("TEXT"); + + b.Property("Region") + .HasColumnType("TEXT"); + + b.HasKey("SupplierId"); + + b.ToTable("Suppliers"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.TerritoryDb", b => + { + b.Property("TerritoryId") + .HasColumnType("TEXT"); + + b.Property("RegionId") + .HasColumnType("INTEGER"); + + b.Property("TerritoryDescription") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("TerritoryId"); + + b.HasIndex("RegionId"); + + b.ToTable("Territories"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.UserDb", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("UserId"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CustomerDb", b => + { + b.OwnsOne("NorthwindCRUD.Models.DbModels.AddressDb", "Address", b1 => + { + b1.Property("CustomerDbCustomerId") + .HasColumnType("TEXT"); + + b1.Property("City") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Country") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Phone") + .HasColumnType("TEXT"); + + b1.Property("PostalCode") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Region") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Street") + .IsRequired() + .HasColumnType("TEXT"); + + b1.HasKey("CustomerDbCustomerId"); + + b1.ToTable("Customers"); + + b1.WithOwner() + .HasForeignKey("CustomerDbCustomerId"); + }); + + b.Navigation("Address") + .IsRequired(); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeDb", b => + { + b.OwnsOne("NorthwindCRUD.Models.DbModels.AddressDb", "Address", b1 => + { + b1.Property("EmployeeDbEmployeeId") + .HasColumnType("INTEGER"); + + b1.Property("City") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Country") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Phone") + .HasColumnType("TEXT"); + + b1.Property("PostalCode") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Region") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Street") + .IsRequired() + .HasColumnType("TEXT"); + + b1.HasKey("EmployeeDbEmployeeId"); + + b1.ToTable("Employees"); + + b1.WithOwner() + .HasForeignKey("EmployeeDbEmployeeId"); + }); + + b.Navigation("Address") + .IsRequired(); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeTerritoryDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.EmployeeDb", "Employee") + .WithMany("EmployeesTerritories") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NorthwindCRUD.Models.DbModels.TerritoryDb", "Territory") + .WithMany("EmployeesTerritories") + .HasForeignKey("TerritoryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Employee"); + + b.Navigation("Territory"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.OrderDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.CustomerDb", "Customer") + .WithMany("Orders") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("NorthwindCRUD.Models.DbModels.EmployeeDb", "Employee") + .WithMany("Orders") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("NorthwindCRUD.Models.DbModels.ShipperDb", "Shipper") + .WithMany("Orders") + .HasForeignKey("ShipperId") + .OnDelete(DeleteBehavior.SetNull); + + b.OwnsOne("NorthwindCRUD.Models.DbModels.AddressDb", "ShipAddress", b1 => + { + b1.Property("OrderDbOrderId") + .HasColumnType("INTEGER"); + + b1.Property("City") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Country") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Phone") + .HasColumnType("TEXT"); + + b1.Property("PostalCode") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Region") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Street") + .IsRequired() + .HasColumnType("TEXT"); + + b1.HasKey("OrderDbOrderId"); + + b1.ToTable("Orders"); + + b1.WithOwner() + .HasForeignKey("OrderDbOrderId"); + }); + + b.Navigation("Customer"); + + b.Navigation("Employee"); + + b.Navigation("ShipAddress"); + + b.Navigation("Shipper"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.OrderDetailDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.OrderDb", "Order") + .WithMany() + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NorthwindCRUD.Models.DbModels.ProductDb", "Product") + .WithMany("Details") + .HasForeignKey("ProductId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Order"); + + b.Navigation("Product"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ProductDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.CategoryDb", "Category") + .WithMany("Products") + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("NorthwindCRUD.Models.DbModels.SupplierDb", "Supplier") + .WithMany("Products") + .HasForeignKey("SupplierId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Category"); + + b.Navigation("Supplier"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.TerritoryDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.RegionDb", "Region") + .WithMany("Territories") + .HasForeignKey("RegionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Region"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CategoryDb", b => + { + b.Navigation("Products"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CustomerDb", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeDb", b => + { + b.Navigation("EmployeesTerritories"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ProductDb", b => + { + b.Navigation("Details"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.RegionDb", b => + { + b.Navigation("Territories"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ShipperDb", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.SupplierDb", b => + { + b.Navigation("Products"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.TerritoryDb", b => + { + b.Navigation("EmployeesTerritories"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.cs b/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.cs new file mode 100644 index 0000000..e05a809 --- /dev/null +++ b/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.cs @@ -0,0 +1,1084 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace NorthwindCRUD.Migrations +{ + public partial class TablesToOwnAddress : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Customers_Addresses_AddressId", + table: "Customers"); + + migrationBuilder.DropForeignKey( + name: "FK_Employees_Addresses_AddressId", + table: "Employees"); + + migrationBuilder.DropForeignKey( + name: "FK_Orders_Addresses_ShipAddressId", + table: "Orders"); + + migrationBuilder.DropTable( + name: "Addresses"); + + migrationBuilder.DropIndex( + name: "IX_Orders_ShipAddressId", + table: "Orders"); + + migrationBuilder.DropIndex( + name: "IX_Employees_AddressId", + table: "Employees"); + + migrationBuilder.DropIndex( + name: "IX_Customers_AddressId", + table: "Customers"); + + migrationBuilder.DropColumn( + name: "ShipAddressId", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "AddressId", + table: "Employees"); + + migrationBuilder.DropColumn( + name: "AddressId", + table: "Customers"); + + migrationBuilder.AlterColumn( + name: "Password", + table: "Users", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "Email", + table: "Users", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "UserId", + table: "Users", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(450)"); + + migrationBuilder.AlterColumn( + name: "ShipVia", + table: "Orders", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "int"); + + migrationBuilder.AlterColumn( + name: "ShipName", + table: "Orders", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "RequiredDate", + table: "Orders", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "OrderDate", + table: "Orders", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "Freight", + table: "Orders", + type: "REAL", + nullable: false, + oldClrType: typeof(double), + oldType: "float"); + + migrationBuilder.AlterColumn( + name: "EmployeeId", + table: "Orders", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "int"); + + migrationBuilder.AlterColumn( + name: "CustomerId", + table: "Orders", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "OrderId", + table: "Orders", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "int"); + + migrationBuilder.AddColumn( + name: "Discount", + table: "Orders", + type: "REAL", + nullable: false, + defaultValue: 0f); + + migrationBuilder.AddColumn( + name: "Quantity", + table: "Orders", + type: "INTEGER", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "ShipAddress_City", + table: "Orders", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "ShipAddress_Country", + table: "Orders", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "ShipAddress_Phone", + table: "Orders", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "ShipAddress_PostalCode", + table: "Orders", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "ShipAddress_Region", + table: "Orders", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "ShipAddress_Street", + table: "Orders", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "ShipperId", + table: "Orders", + type: "INTEGER", + nullable: true); + + migrationBuilder.AddColumn( + name: "UnitPrice", + table: "Orders", + type: "REAL", + nullable: false, + defaultValue: 0.0); + + migrationBuilder.AlterColumn( + name: "TitleOfCourtesy", + table: "Employees", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "Title", + table: "Employees", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "Notes", + table: "Employees", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "LastName", + table: "Employees", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "HireDate", + table: "Employees", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "FirstName", + table: "Employees", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "BirthDate", + table: "Employees", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "AvatarUrl", + table: "Employees", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "EmployeeId", + table: "Employees", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "int"); + + migrationBuilder.AddColumn( + name: "Address_City", + table: "Employees", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Address_Country", + table: "Employees", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Address_Phone", + table: "Employees", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "Address_PostalCode", + table: "Employees", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Address_Region", + table: "Employees", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Address_Street", + table: "Employees", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "ReportsTo", + table: "Employees", + type: "INTEGER", + nullable: false, + defaultValue: 0); + + migrationBuilder.AlterColumn( + name: "ContactTitle", + table: "Customers", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "ContactName", + table: "Customers", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "CompanyName", + table: "Customers", + type: "TEXT", + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "nvarchar(max)", + oldNullable: true); + + migrationBuilder.AlterColumn( + name: "CustomerId", + table: "Customers", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(450)"); + + migrationBuilder.AddColumn( + name: "Address_City", + table: "Customers", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Address_Country", + table: "Customers", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Address_Phone", + table: "Customers", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "Address_PostalCode", + table: "Customers", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Address_Region", + table: "Customers", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Address_Street", + table: "Customers", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.AlterColumn( + name: "Name", + table: "Categories", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "Description", + table: "Categories", + type: "TEXT", + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + + migrationBuilder.AlterColumn( + name: "CategoryId", + table: "Categories", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "int") + .Annotation("Sqlite:Autoincrement", true); + + migrationBuilder.AddColumn( + name: "Picture", + table: "Categories", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.CreateTable( + name: "Regions", + columns: table => new + { + RegionId = table.Column(type: "INTEGER", nullable: false), + RegionDescription = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Regions", x => x.RegionId); + }); + + migrationBuilder.CreateTable( + name: "Shippers", + columns: table => new + { + ShipperId = table.Column(type: "INTEGER", nullable: false), + CompanyName = table.Column(type: "TEXT", nullable: false), + Phone = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shippers", x => x.ShipperId); + }); + + migrationBuilder.CreateTable( + name: "Suppliers", + columns: table => new + { + SupplierId = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + CompanyName = table.Column(type: "TEXT", nullable: true), + ContactName = table.Column(type: "TEXT", nullable: true), + ContactTitle = table.Column(type: "TEXT", nullable: true), + Address = table.Column(type: "TEXT", nullable: true), + City = table.Column(type: "TEXT", nullable: true), + Region = table.Column(type: "TEXT", nullable: true), + PostalCode = table.Column(type: "TEXT", nullable: true), + Country = table.Column(type: "TEXT", nullable: true), + Phone = table.Column(type: "TEXT", nullable: true), + Fax = table.Column(type: "TEXT", nullable: true), + HomePage = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Suppliers", x => x.SupplierId); + }); + + migrationBuilder.CreateTable( + name: "Territories", + columns: table => new + { + TerritoryId = table.Column(type: "TEXT", nullable: false), + RegionId = table.Column(type: "INTEGER", nullable: true), + TerritoryDescription = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Territories", x => x.TerritoryId); + table.ForeignKey( + name: "FK_Territories_Regions_RegionId", + column: x => x.RegionId, + principalTable: "Regions", + principalColumn: "RegionId", + onDelete: ReferentialAction.SetNull); + }); + + migrationBuilder.CreateTable( + name: "Products", + columns: table => new + { + ProductId = table.Column(type: "INTEGER", nullable: false), + SupplierId = table.Column(type: "INTEGER", nullable: true), + CategoryId = table.Column(type: "INTEGER", nullable: true), + QuantityPerUnit = table.Column(type: "TEXT", nullable: false), + UnitPrice = table.Column(type: "REAL", nullable: true), + UnitsInStock = table.Column(type: "INTEGER", nullable: true), + UnitsOnOrder = table.Column(type: "INTEGER", nullable: true), + ReorderLevel = table.Column(type: "INTEGER", nullable: true), + Discontinued = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Products", x => x.ProductId); + table.ForeignKey( + name: "FK_Products_Categories_CategoryId", + column: x => x.CategoryId, + principalTable: "Categories", + principalColumn: "CategoryId", + onDelete: ReferentialAction.SetNull); + table.ForeignKey( + name: "FK_Products_Suppliers_SupplierId", + column: x => x.SupplierId, + principalTable: "Suppliers", + principalColumn: "SupplierId", + onDelete: ReferentialAction.SetNull); + }); + + migrationBuilder.CreateTable( + name: "EmployeesTerritories", + columns: table => new + { + EmployeeId = table.Column(type: "INTEGER", nullable: false), + TerritoryId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_EmployeesTerritories", x => new { x.EmployeeId, x.TerritoryId }); + table.ForeignKey( + name: "FK_EmployeesTerritories_Employees_EmployeeId", + column: x => x.EmployeeId, + principalTable: "Employees", + principalColumn: "EmployeeId", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_EmployeesTerritories_Territories_TerritoryId", + column: x => x.TerritoryId, + principalTable: "Territories", + principalColumn: "TerritoryId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OrderDetails", + columns: table => new + { + OrderId = table.Column(type: "INTEGER", nullable: false), + ProductId = table.Column(type: "INTEGER", nullable: false), + UnitPrice = table.Column(type: "REAL", nullable: false), + Quantity = table.Column(type: "INTEGER", nullable: false), + Discount = table.Column(type: "REAL", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OrderDetails", x => new { x.ProductId, x.OrderId }); + table.ForeignKey( + name: "FK_OrderDetails_Orders_OrderId", + column: x => x.OrderId, + principalTable: "Orders", + principalColumn: "OrderId", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_OrderDetails_Products_ProductId", + column: x => x.ProductId, + principalTable: "Products", + principalColumn: "ProductId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Orders_CustomerId", + table: "Orders", + column: "CustomerId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_EmployeeId", + table: "Orders", + column: "EmployeeId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ShipperId", + table: "Orders", + column: "ShipperId"); + + migrationBuilder.CreateIndex( + name: "IX_EmployeesTerritories_TerritoryId", + table: "EmployeesTerritories", + column: "TerritoryId"); + + migrationBuilder.CreateIndex( + name: "IX_OrderDetails_OrderId", + table: "OrderDetails", + column: "OrderId"); + + migrationBuilder.CreateIndex( + name: "IX_Products_CategoryId", + table: "Products", + column: "CategoryId"); + + migrationBuilder.CreateIndex( + name: "IX_Products_SupplierId", + table: "Products", + column: "SupplierId"); + + migrationBuilder.CreateIndex( + name: "IX_Territories_RegionId", + table: "Territories", + column: "RegionId"); + + migrationBuilder.AddForeignKey( + name: "FK_Orders_Customers_CustomerId", + table: "Orders", + column: "CustomerId", + principalTable: "Customers", + principalColumn: "CustomerId", + onDelete: ReferentialAction.SetNull); + + migrationBuilder.AddForeignKey( + name: "FK_Orders_Employees_EmployeeId", + table: "Orders", + column: "EmployeeId", + principalTable: "Employees", + principalColumn: "EmployeeId", + onDelete: ReferentialAction.SetNull); + + migrationBuilder.AddForeignKey( + name: "FK_Orders_Shippers_ShipperId", + table: "Orders", + column: "ShipperId", + principalTable: "Shippers", + principalColumn: "ShipperId", + onDelete: ReferentialAction.SetNull); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Orders_Customers_CustomerId", + table: "Orders"); + + migrationBuilder.DropForeignKey( + name: "FK_Orders_Employees_EmployeeId", + table: "Orders"); + + migrationBuilder.DropForeignKey( + name: "FK_Orders_Shippers_ShipperId", + table: "Orders"); + + migrationBuilder.DropTable( + name: "EmployeesTerritories"); + + migrationBuilder.DropTable( + name: "OrderDetails"); + + migrationBuilder.DropTable( + name: "Shippers"); + + migrationBuilder.DropTable( + name: "Territories"); + + migrationBuilder.DropTable( + name: "Products"); + + migrationBuilder.DropTable( + name: "Regions"); + + migrationBuilder.DropTable( + name: "Suppliers"); + + migrationBuilder.DropIndex( + name: "IX_Orders_CustomerId", + table: "Orders"); + + migrationBuilder.DropIndex( + name: "IX_Orders_EmployeeId", + table: "Orders"); + + migrationBuilder.DropIndex( + name: "IX_Orders_ShipperId", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "Discount", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "Quantity", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "ShipAddress_City", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "ShipAddress_Country", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "ShipAddress_Phone", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "ShipAddress_PostalCode", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "ShipAddress_Region", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "ShipAddress_Street", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "ShipperId", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "UnitPrice", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "Address_City", + table: "Employees"); + + migrationBuilder.DropColumn( + name: "Address_Country", + table: "Employees"); + + migrationBuilder.DropColumn( + name: "Address_Phone", + table: "Employees"); + + migrationBuilder.DropColumn( + name: "Address_PostalCode", + table: "Employees"); + + migrationBuilder.DropColumn( + name: "Address_Region", + table: "Employees"); + + migrationBuilder.DropColumn( + name: "Address_Street", + table: "Employees"); + + migrationBuilder.DropColumn( + name: "ReportsTo", + table: "Employees"); + + migrationBuilder.DropColumn( + name: "Address_City", + table: "Customers"); + + migrationBuilder.DropColumn( + name: "Address_Country", + table: "Customers"); + + migrationBuilder.DropColumn( + name: "Address_Phone", + table: "Customers"); + + migrationBuilder.DropColumn( + name: "Address_PostalCode", + table: "Customers"); + + migrationBuilder.DropColumn( + name: "Address_Region", + table: "Customers"); + + migrationBuilder.DropColumn( + name: "Address_Street", + table: "Customers"); + + migrationBuilder.DropColumn( + name: "Picture", + table: "Categories"); + + migrationBuilder.AlterColumn( + name: "Password", + table: "Users", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "Email", + table: "Users", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "UserId", + table: "Users", + type: "nvarchar(450)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "ShipVia", + table: "Orders", + type: "int", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER"); + + migrationBuilder.AlterColumn( + name: "ShipName", + table: "Orders", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "RequiredDate", + table: "Orders", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "OrderDate", + table: "Orders", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "Freight", + table: "Orders", + type: "float", + nullable: false, + oldClrType: typeof(double), + oldType: "REAL"); + + migrationBuilder.AlterColumn( + name: "EmployeeId", + table: "Orders", + type: "int", + nullable: false, + defaultValue: 0, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true); + + migrationBuilder.AlterColumn( + name: "CustomerId", + table: "Orders", + type: "nvarchar(max)", + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true); + + migrationBuilder.AlterColumn( + name: "OrderId", + table: "Orders", + type: "int", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER"); + + migrationBuilder.AddColumn( + name: "ShipAddressId", + table: "Orders", + type: "nvarchar(450)", + nullable: false, + defaultValue: ""); + + migrationBuilder.AlterColumn( + name: "TitleOfCourtesy", + table: "Employees", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "Title", + table: "Employees", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "Notes", + table: "Employees", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "LastName", + table: "Employees", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "HireDate", + table: "Employees", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "FirstName", + table: "Employees", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "BirthDate", + table: "Employees", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "AvatarUrl", + table: "Employees", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "EmployeeId", + table: "Employees", + type: "int", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER"); + + migrationBuilder.AddColumn( + name: "AddressId", + table: "Employees", + type: "nvarchar(450)", + nullable: false, + defaultValue: ""); + + migrationBuilder.AlterColumn( + name: "ContactTitle", + table: "Customers", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "ContactName", + table: "Customers", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "CompanyName", + table: "Customers", + type: "nvarchar(max)", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "CustomerId", + table: "Customers", + type: "nvarchar(450)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AddColumn( + name: "AddressId", + table: "Customers", + type: "nvarchar(450)", + nullable: false, + defaultValue: ""); + + migrationBuilder.AlterColumn( + name: "Name", + table: "Categories", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "Description", + table: "Categories", + type: "nvarchar(max)", + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT"); + + migrationBuilder.AlterColumn( + name: "CategoryId", + table: "Categories", + type: "int", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") + .OldAnnotation("Sqlite:Autoincrement", true); + + migrationBuilder.CreateTable( + name: "Addresses", + columns: table => new + { + AddressId = table.Column(type: "nvarchar(450)", nullable: false), + City = table.Column(type: "nvarchar(max)", nullable: false), + Country = table.Column(type: "nvarchar(max)", nullable: false), + Phone = table.Column(type: "nvarchar(max)", nullable: false), + PostalCode = table.Column(type: "nvarchar(max)", nullable: false), + Region = table.Column(type: "nvarchar(max)", nullable: false), + Street = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Addresses", x => x.AddressId); + }); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ShipAddressId", + table: "Orders", + column: "ShipAddressId"); + + migrationBuilder.CreateIndex( + name: "IX_Employees_AddressId", + table: "Employees", + column: "AddressId"); + + migrationBuilder.CreateIndex( + name: "IX_Customers_AddressId", + table: "Customers", + column: "AddressId"); + + migrationBuilder.AddForeignKey( + name: "FK_Customers_Addresses_AddressId", + table: "Customers", + column: "AddressId", + principalTable: "Addresses", + principalColumn: "AddressId", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_Employees_Addresses_AddressId", + table: "Employees", + column: "AddressId", + principalTable: "Addresses", + principalColumn: "AddressId", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_Orders_Addresses_ShipAddressId", + table: "Orders", + column: "ShipAddressId", + principalTable: "Addresses", + principalColumn: "AddressId", + onDelete: ReferentialAction.Cascade); + } + } +} diff --git a/NorthwindCRUD/Migrations/DataContextModelSnapshot.cs b/NorthwindCRUD/Migrations/DataContextModelSnapshot.cs index fd85b96..f008410 100644 --- a/NorthwindCRUD/Migrations/DataContextModelSnapshot.cs +++ b/NorthwindCRUD/Migrations/DataContextModelSnapshot.cs @@ -1,7 +1,7 @@ // +using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using NorthwindCRUD; @@ -15,59 +15,25 @@ partial class DataContextModelSnapshot : ModelSnapshot protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "6.0.8") - .HasAnnotation("Relational:MaxIdentifierLength", 128); - - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); - - modelBuilder.Entity("NorthwindCRUD.Models.DbModels.AddressDb", b => - { - b.Property("AddressId") - .ValueGeneratedOnAdd() - .HasColumnType("nvarchar(450)"); - - b.Property("City") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Country") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Phone") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("PostalCode") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Region") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Street") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.HasKey("AddressId"); - - b.ToTable("Addresses"); - }); + modelBuilder.HasAnnotation("ProductVersion", "6.0.22"); modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CategoryDb", b => { b.Property("CategoryId") - .HasColumnType("int"); + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); b.Property("Description") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("Name") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); + + b.Property("Picture") + .IsRequired() + .HasColumnType("TEXT"); b.HasKey("CategoryId"); @@ -77,131 +43,307 @@ protected override void BuildModel(ModelBuilder modelBuilder) modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CustomerDb", b => { b.Property("CustomerId") - .HasColumnType("nvarchar(450)"); - - b.Property("AddressId") - .IsRequired() - .HasColumnType("nvarchar(450)"); + .HasColumnType("TEXT"); b.Property("CompanyName") - .HasColumnType("nvarchar(max)"); + .IsRequired() + .HasColumnType("TEXT"); b.Property("ContactName") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("ContactTitle") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.HasKey("CustomerId"); - b.HasIndex("AddressId"); - b.ToTable("Customers"); }); modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeDb", b => { b.Property("EmployeeId") - .HasColumnType("int"); - - b.Property("AddressId") - .IsRequired() - .HasColumnType("nvarchar(450)"); + .HasColumnType("INTEGER"); b.Property("AvatarUrl") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("BirthDate") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("FirstName") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("HireDate") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("LastName") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("Notes") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); + + b.Property("ReportsTo") + .HasColumnType("INTEGER"); b.Property("Title") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("TitleOfCourtesy") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.HasKey("EmployeeId"); - b.HasIndex("AddressId"); - b.ToTable("Employees"); }); + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeTerritoryDb", b => + { + b.Property("EmployeeId") + .HasColumnType("INTEGER"); + + b.Property("TerritoryId") + .HasColumnType("TEXT"); + + b.HasKey("EmployeeId", "TerritoryId"); + + b.HasIndex("TerritoryId"); + + b.ToTable("EmployeesTerritories"); + }); + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.OrderDb", b => { b.Property("OrderId") - .HasColumnType("int"); + .HasColumnType("INTEGER"); b.Property("CustomerId") - .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); - b.Property("EmployeeId") - .HasColumnType("int"); + b.Property("Discount") + .HasColumnType("REAL"); + + b.Property("EmployeeId") + .HasColumnType("INTEGER"); b.Property("Freight") - .HasColumnType("float"); + .HasColumnType("REAL"); b.Property("OrderDate") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); - b.Property("RequiredDate") - .IsRequired() - .HasColumnType("nvarchar(max)"); + b.Property("Quantity") + .HasColumnType("INTEGER"); - b.Property("ShipAddressId") + b.Property("RequiredDate") .IsRequired() - .HasColumnType("nvarchar(450)"); + .HasColumnType("TEXT"); b.Property("ShipName") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("ShipVia") - .HasColumnType("int"); + .HasColumnType("INTEGER"); + + b.Property("ShipperId") + .HasColumnType("INTEGER"); + + b.Property("UnitPrice") + .HasColumnType("REAL"); b.HasKey("OrderId"); - b.HasIndex("ShipAddressId"); + b.HasIndex("CustomerId"); + + b.HasIndex("EmployeeId"); + + b.HasIndex("ShipperId"); b.ToTable("Orders"); }); + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.OrderDetailDb", b => + { + b.Property("ProductId") + .HasColumnType("INTEGER"); + + b.Property("OrderId") + .HasColumnType("INTEGER"); + + b.Property("Discount") + .HasColumnType("REAL"); + + b.Property("Quantity") + .HasColumnType("INTEGER"); + + b.Property("UnitPrice") + .HasColumnType("REAL"); + + b.HasKey("ProductId", "OrderId"); + + b.HasIndex("OrderId"); + + b.ToTable("OrderDetails"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ProductDb", b => + { + b.Property("ProductId") + .HasColumnType("INTEGER"); + + b.Property("CategoryId") + .HasColumnType("INTEGER"); + + b.Property("Discontinued") + .HasColumnType("INTEGER"); + + b.Property("QuantityPerUnit") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReorderLevel") + .HasColumnType("INTEGER"); + + b.Property("SupplierId") + .HasColumnType("INTEGER"); + + b.Property("UnitPrice") + .HasColumnType("REAL"); + + b.Property("UnitsInStock") + .HasColumnType("INTEGER"); + + b.Property("UnitsOnOrder") + .HasColumnType("INTEGER"); + + b.HasKey("ProductId"); + + b.HasIndex("CategoryId"); + + b.HasIndex("SupplierId"); + + b.ToTable("Products"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.RegionDb", b => + { + b.Property("RegionId") + .HasColumnType("INTEGER"); + + b.Property("RegionDescription") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("RegionId"); + + b.ToTable("Regions"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ShipperDb", b => + { + b.Property("ShipperId") + .HasColumnType("INTEGER"); + + b.Property("CompanyName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Phone") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("ShipperId"); + + b.ToTable("Shippers"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.SupplierDb", b => + { + b.Property("SupplierId") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Address") + .HasColumnType("TEXT"); + + b.Property("City") + .HasColumnType("TEXT"); + + b.Property("CompanyName") + .HasColumnType("TEXT"); + + b.Property("ContactName") + .HasColumnType("TEXT"); + + b.Property("ContactTitle") + .HasColumnType("TEXT"); + + b.Property("Country") + .HasColumnType("TEXT"); + + b.Property("Fax") + .HasColumnType("TEXT"); + + b.Property("HomePage") + .HasColumnType("TEXT"); + + b.Property("Phone") + .HasColumnType("TEXT"); + + b.Property("PostalCode") + .HasColumnType("TEXT"); + + b.Property("Region") + .HasColumnType("TEXT"); + + b.HasKey("SupplierId"); + + b.ToTable("Suppliers"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.TerritoryDb", b => + { + b.Property("TerritoryId") + .HasColumnType("TEXT"); + + b.Property("RegionId") + .HasColumnType("INTEGER"); + + b.Property("TerritoryDescription") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("TerritoryId"); + + b.HasIndex("RegionId"); + + b.ToTable("Territories"); + }); + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.UserDb", b => { b.Property("UserId") - .HasColumnType("nvarchar(450)"); + .HasColumnType("TEXT"); b.Property("Email") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.Property("Password") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasColumnType("TEXT"); b.HasKey("UserId"); @@ -210,45 +352,256 @@ protected override void BuildModel(ModelBuilder modelBuilder) modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CustomerDb", b => { - b.HasOne("NorthwindCRUD.Models.DbModels.AddressDb", "Address") - .WithMany("Customers") - .HasForeignKey("AddressId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + b.OwnsOne("NorthwindCRUD.Models.DbModels.AddressDb", "Address", b1 => + { + b1.Property("CustomerDbCustomerId") + .HasColumnType("TEXT"); + + b1.Property("City") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Country") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Phone") + .HasColumnType("TEXT"); + + b1.Property("PostalCode") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Region") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Street") + .IsRequired() + .HasColumnType("TEXT"); - b.Navigation("Address"); + b1.HasKey("CustomerDbCustomerId"); + + b1.ToTable("Customers"); + + b1.WithOwner() + .HasForeignKey("CustomerDbCustomerId"); + }); + + b.Navigation("Address") + .IsRequired(); }); modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeDb", b => { - b.HasOne("NorthwindCRUD.Models.DbModels.AddressDb", "Address") - .WithMany("Employees") - .HasForeignKey("AddressId") + b.OwnsOne("NorthwindCRUD.Models.DbModels.AddressDb", "Address", b1 => + { + b1.Property("EmployeeDbEmployeeId") + .HasColumnType("INTEGER"); + + b1.Property("City") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Country") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Phone") + .HasColumnType("TEXT"); + + b1.Property("PostalCode") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Region") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Street") + .IsRequired() + .HasColumnType("TEXT"); + + b1.HasKey("EmployeeDbEmployeeId"); + + b1.ToTable("Employees"); + + b1.WithOwner() + .HasForeignKey("EmployeeDbEmployeeId"); + }); + + b.Navigation("Address") + .IsRequired(); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeTerritoryDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.EmployeeDb", "Employee") + .WithMany("EmployeesTerritories") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NorthwindCRUD.Models.DbModels.TerritoryDb", "Territory") + .WithMany("EmployeesTerritories") + .HasForeignKey("TerritoryId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.Navigation("Address"); + b.Navigation("Employee"); + + b.Navigation("Territory"); }); modelBuilder.Entity("NorthwindCRUD.Models.DbModels.OrderDb", b => { - b.HasOne("NorthwindCRUD.Models.DbModels.AddressDb", "ShipAddress") + b.HasOne("NorthwindCRUD.Models.DbModels.CustomerDb", "Customer") + .WithMany("Orders") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("NorthwindCRUD.Models.DbModels.EmployeeDb", "Employee") .WithMany("Orders") - .HasForeignKey("ShipAddressId") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("NorthwindCRUD.Models.DbModels.ShipperDb", "Shipper") + .WithMany("Orders") + .HasForeignKey("ShipperId") + .OnDelete(DeleteBehavior.SetNull); + + b.OwnsOne("NorthwindCRUD.Models.DbModels.AddressDb", "ShipAddress", b1 => + { + b1.Property("OrderDbOrderId") + .HasColumnType("INTEGER"); + + b1.Property("City") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Country") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Phone") + .HasColumnType("TEXT"); + + b1.Property("PostalCode") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Region") + .IsRequired() + .HasColumnType("TEXT"); + + b1.Property("Street") + .IsRequired() + .HasColumnType("TEXT"); + + b1.HasKey("OrderDbOrderId"); + + b1.ToTable("Orders"); + + b1.WithOwner() + .HasForeignKey("OrderDbOrderId"); + }); + + b.Navigation("Customer"); + + b.Navigation("Employee"); + + b.Navigation("ShipAddress"); + + b.Navigation("Shipper"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.OrderDetailDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.OrderDb", "Order") + .WithMany() + .HasForeignKey("OrderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.Navigation("ShipAddress"); + b.HasOne("NorthwindCRUD.Models.DbModels.ProductDb", "Product") + .WithMany("Details") + .HasForeignKey("ProductId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Order"); + + b.Navigation("Product"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ProductDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.CategoryDb", "Category") + .WithMany("Products") + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("NorthwindCRUD.Models.DbModels.SupplierDb", "Supplier") + .WithMany("Products") + .HasForeignKey("SupplierId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Category"); + + b.Navigation("Supplier"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.TerritoryDb", b => + { + b.HasOne("NorthwindCRUD.Models.DbModels.RegionDb", "Region") + .WithMany("Territories") + .HasForeignKey("RegionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Region"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CategoryDb", b => + { + b.Navigation("Products"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.CustomerDb", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.EmployeeDb", b => + { + b.Navigation("EmployeesTerritories"); + + b.Navigation("Orders"); }); - modelBuilder.Entity("NorthwindCRUD.Models.DbModels.AddressDb", b => + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ProductDb", b => { - b.Navigation("Customers"); + b.Navigation("Details"); + }); - b.Navigation("Employees"); + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.RegionDb", b => + { + b.Navigation("Territories"); + }); + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.ShipperDb", b => + { b.Navigation("Orders"); }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.SupplierDb", b => + { + b.Navigation("Products"); + }); + + modelBuilder.Entity("NorthwindCRUD.Models.DbModels.TerritoryDb", b => + { + b.Navigation("EmployeesTerritories"); + }); #pragma warning restore 612, 618 } } diff --git a/NorthwindCRUD/Models/Contracts/IAddress.cs b/NorthwindCRUD/Models/Contracts/IAddress.cs index 5d9a55c..0f47f1d 100644 --- a/NorthwindCRUD/Models/Contracts/IAddress.cs +++ b/NorthwindCRUD/Models/Contracts/IAddress.cs @@ -1,6 +1,4 @@ -using NorthwindCRUD.Models.DbModels; - -namespace NorthwindCRUD.Models.Contracts +namespace NorthwindCRUD.Models.Contracts { public interface IAddress { diff --git a/NorthwindCRUD/Models/Contracts/ICategory.cs b/NorthwindCRUD/Models/Contracts/ICategory.cs index 0826e3d..8596d43 100644 --- a/NorthwindCRUD/Models/Contracts/ICategory.cs +++ b/NorthwindCRUD/Models/Contracts/ICategory.cs @@ -2,7 +2,7 @@ { public interface ICategory { - int CategoryId { get; set; } + int CategoryId { get; } string Description { get; set; } diff --git a/NorthwindCRUD/Models/Contracts/ICustomer.cs b/NorthwindCRUD/Models/Contracts/ICustomer.cs index 3f05c49..ca37dc8 100644 --- a/NorthwindCRUD/Models/Contracts/ICustomer.cs +++ b/NorthwindCRUD/Models/Contracts/ICustomer.cs @@ -1,10 +1,8 @@ -using NorthwindCRUD.Models.DbModels; - -namespace NorthwindCRUD.Models.Contracts +namespace NorthwindCRUD.Models.Contracts { public interface ICustomer { - string CustomerId { get; set; } + string CustomerId { get; } string CompanyName { get; set; } diff --git a/NorthwindCRUD/Models/Contracts/IEmployee.cs b/NorthwindCRUD/Models/Contracts/IEmployee.cs index 62f4428..6541c77 100644 --- a/NorthwindCRUD/Models/Contracts/IEmployee.cs +++ b/NorthwindCRUD/Models/Contracts/IEmployee.cs @@ -1,10 +1,8 @@ -using NorthwindCRUD.Models.DbModels; - -namespace NorthwindCRUD.Models.Contracts +namespace NorthwindCRUD.Models.Contracts { public interface IEmployee { - int EmployeeId { get; set; } + int EmployeeId { get; } string LastName { get; set; } diff --git a/NorthwindCRUD/Models/Contracts/IEmployeeTerritory.cs b/NorthwindCRUD/Models/Contracts/IEmployeeTerritory.cs index 49f12b7..b52b3e2 100644 --- a/NorthwindCRUD/Models/Contracts/IEmployeeTerritory.cs +++ b/NorthwindCRUD/Models/Contracts/IEmployeeTerritory.cs @@ -1,5 +1,3 @@ -using NorthwindCRUD.Models.DbModels; - namespace NorthwindCRUD.Models.Contracts { public interface IEmployeeTerritory diff --git a/NorthwindCRUD/Models/Contracts/IOrder.cs b/NorthwindCRUD/Models/Contracts/IOrder.cs index 203338c..341c70d 100644 --- a/NorthwindCRUD/Models/Contracts/IOrder.cs +++ b/NorthwindCRUD/Models/Contracts/IOrder.cs @@ -1,12 +1,10 @@ -using NorthwindCRUD.Models.DbModels; -using NorthwindCRUD.Models.Dtos; -using NorthwindCRUD.Models.InputModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Models.Contracts { public interface IOrder { - int OrderId { get; set; } + int OrderId { get; } string CustomerId { get; set; } diff --git a/NorthwindCRUD/Models/Contracts/IProduct.cs b/NorthwindCRUD/Models/Contracts/IProduct.cs index 072cbc8..66bd316 100644 --- a/NorthwindCRUD/Models/Contracts/IProduct.cs +++ b/NorthwindCRUD/Models/Contracts/IProduct.cs @@ -2,7 +2,7 @@ { public interface IProduct { - int ProductId { get; set; } + int ProductId { get; } int? SupplierId { get; set; } diff --git a/NorthwindCRUD/Models/Contracts/IRegion.cs b/NorthwindCRUD/Models/Contracts/IRegion.cs index 95f3b08..9cb7657 100644 --- a/NorthwindCRUD/Models/Contracts/IRegion.cs +++ b/NorthwindCRUD/Models/Contracts/IRegion.cs @@ -2,7 +2,7 @@ { public interface IRegion { - int RegionId { get; set; } + int RegionId { get; } string RegionDescription { get; set; } } diff --git a/NorthwindCRUD/Models/Contracts/IShipper.cs b/NorthwindCRUD/Models/Contracts/IShipper.cs index e8321a0..1926125 100644 --- a/NorthwindCRUD/Models/Contracts/IShipper.cs +++ b/NorthwindCRUD/Models/Contracts/IShipper.cs @@ -2,10 +2,10 @@ { public interface IShipper { - int ShipperId { get; set; } + int ShipperId { get; } - string CompanyName { get; set; } + string CompanyName { get; set; } - string Phone { get; set; } + string Phone { get; set; } } } diff --git a/NorthwindCRUD/Models/Contracts/ISupplier.cs b/NorthwindCRUD/Models/Contracts/ISupplier.cs index 264a424..5f45064 100644 --- a/NorthwindCRUD/Models/Contracts/ISupplier.cs +++ b/NorthwindCRUD/Models/Contracts/ISupplier.cs @@ -2,7 +2,7 @@ { public interface ISupplier { - int SupplierId { get; set; } + int SupplierId { get; } string? CompanyName { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/AddressDb.cs b/NorthwindCRUD/Models/DbModels/AddressDb.cs index be7d33d..0907a34 100644 --- a/NorthwindCRUD/Models/DbModels/AddressDb.cs +++ b/NorthwindCRUD/Models/DbModels/AddressDb.cs @@ -1,14 +1,9 @@ -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using NorthwindCRUD.Models.Contracts; +using NorthwindCRUD.Models.Contracts; namespace NorthwindCRUD.Models.DbModels { public class AddressDb : IBaseDb, IAddress { - [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] - public string AddressId { get; set; } public string Street { get; set; } @@ -21,11 +16,5 @@ public class AddressDb : IBaseDb, IAddress public string Country { get; set; } public string? Phone { get; set; } - - public ICollection Customers { get; set; } - - public ICollection Employees { get; set; } - - public ICollection Orders { get; set; } } } diff --git a/NorthwindCRUD/Models/DbModels/CategoryDb.cs b/NorthwindCRUD/Models/DbModels/CategoryDb.cs index 73b6555..2e2c546 100644 --- a/NorthwindCRUD/Models/DbModels/CategoryDb.cs +++ b/NorthwindCRUD/Models/DbModels/CategoryDb.cs @@ -7,7 +7,7 @@ namespace NorthwindCRUD.Models.DbModels public class CategoryDb : IBaseDb, ICategory, ICategoryDetail { [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int CategoryId { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/CustomerDb.cs b/NorthwindCRUD/Models/DbModels/CustomerDb.cs index 8e9c667..1b74a92 100644 --- a/NorthwindCRUD/Models/DbModels/CustomerDb.cs +++ b/NorthwindCRUD/Models/DbModels/CustomerDb.cs @@ -7,7 +7,7 @@ namespace NorthwindCRUD.Models.DbModels public class CustomerDb : IBaseDb, ICustomer { [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public string CustomerId { get; set; } public string CompanyName { get; set; } @@ -16,15 +16,8 @@ public class CustomerDb : IBaseDb, ICustomer public string ContactTitle { get; set; } - public string AddressId { get; set; } - public AddressDb Address { get; set; } public ICollection Orders { get; set; } - - public string[] GetIncludes() - { - return new string[] { "Address" }; - } } } diff --git a/NorthwindCRUD/Models/DbModels/EmployeeDb.cs b/NorthwindCRUD/Models/DbModels/EmployeeDb.cs index a2376a5..0c4f609 100644 --- a/NorthwindCRUD/Models/DbModels/EmployeeDb.cs +++ b/NorthwindCRUD/Models/DbModels/EmployeeDb.cs @@ -7,7 +7,7 @@ namespace NorthwindCRUD.Models.DbModels public class EmployeeDb : IBaseDb, IEmployee { [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int EmployeeId { get; set; } public string LastName { get; set; } @@ -22,8 +22,6 @@ public class EmployeeDb : IBaseDb, IEmployee public string HireDate { get; set; } - public string AddressId { get; set; } - public AddressDb Address { get; set; } public string Notes { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/OrderDb.cs b/NorthwindCRUD/Models/DbModels/OrderDb.cs index 085bc05..0be3497 100644 --- a/NorthwindCRUD/Models/DbModels/OrderDb.cs +++ b/NorthwindCRUD/Models/DbModels/OrderDb.cs @@ -5,9 +5,8 @@ namespace NorthwindCRUD.Models.DbModels { public class OrderDb : IBaseDb { - [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int OrderId { get; set; } public string? CustomerId { get; set; } @@ -38,8 +37,6 @@ public class OrderDb : IBaseDb public float Discount { get; set; } - public string? ShipAddressId { get; set; } - public AddressDb? ShipAddress { get; set; } } } diff --git a/NorthwindCRUD/Models/DbModels/ProductDb.cs b/NorthwindCRUD/Models/DbModels/ProductDb.cs index 6ab5c09..a84d712 100644 --- a/NorthwindCRUD/Models/DbModels/ProductDb.cs +++ b/NorthwindCRUD/Models/DbModels/ProductDb.cs @@ -7,7 +7,7 @@ namespace NorthwindCRUD.Models.DbModels public class ProductDb : IBaseDb, IProduct { [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ProductId { get; set; } public int? SupplierId { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/RegionDb.cs b/NorthwindCRUD/Models/DbModels/RegionDb.cs index fc2b4fc..7316b87 100644 --- a/NorthwindCRUD/Models/DbModels/RegionDb.cs +++ b/NorthwindCRUD/Models/DbModels/RegionDb.cs @@ -7,7 +7,7 @@ namespace NorthwindCRUD.Models.DbModels public class RegionDb : IBaseDb, IRegion { [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int RegionId { get; set; } public string RegionDescription { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/ShipperDb.cs b/NorthwindCRUD/Models/DbModels/ShipperDb.cs index 7e9c567..10d6664 100644 --- a/NorthwindCRUD/Models/DbModels/ShipperDb.cs +++ b/NorthwindCRUD/Models/DbModels/ShipperDb.cs @@ -7,7 +7,7 @@ namespace NorthwindCRUD.Models.DbModels public class ShipperDb : IBaseDb, IShipper { [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ShipperId { get; set; } public string CompanyName { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/SupplierDb.cs b/NorthwindCRUD/Models/DbModels/SupplierDb.cs index 87df7fb..828e83a 100644 --- a/NorthwindCRUD/Models/DbModels/SupplierDb.cs +++ b/NorthwindCRUD/Models/DbModels/SupplierDb.cs @@ -7,7 +7,7 @@ namespace NorthwindCRUD.Models.DbModels public class SupplierDb : IBaseDb, ISupplier { [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int SupplierId { get; set; } public string? CompanyName { get; set; } diff --git a/NorthwindCRUD/Models/DbModels/TerritoryDb.cs b/NorthwindCRUD/Models/DbModels/TerritoryDb.cs index 51997e7..c62fe08 100644 --- a/NorthwindCRUD/Models/DbModels/TerritoryDb.cs +++ b/NorthwindCRUD/Models/DbModels/TerritoryDb.cs @@ -7,7 +7,7 @@ namespace NorthwindCRUD.Models.DbModels public class TerritoryDb : IBaseDb, ITerritory { [Key] - [DatabaseGenerated(DatabaseGeneratedOption.None)] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public string TerritoryId { get; set; } public int? RegionId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/CategoryDto.cs b/NorthwindCRUD/Models/Dtos/CategoryDto.cs index 05c2926..f25280a 100644 --- a/NorthwindCRUD/Models/Dtos/CategoryDto.cs +++ b/NorthwindCRUD/Models/Dtos/CategoryDto.cs @@ -1,9 +1,11 @@ -using NorthwindCRUD.Models.Contracts; +using System.ComponentModel.DataAnnotations; +using NorthwindCRUD.Models.Contracts; namespace NorthwindCRUD.Models.Dtos { public class CategoryDto : IBaseDto, ICategory { + [Key] public int CategoryId { get; set; } public string Description { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/CustomerDto.cs b/NorthwindCRUD/Models/Dtos/CustomerDto.cs index b415a56..634d805 100644 --- a/NorthwindCRUD/Models/Dtos/CustomerDto.cs +++ b/NorthwindCRUD/Models/Dtos/CustomerDto.cs @@ -5,6 +5,7 @@ namespace NorthwindCRUD.Models.Dtos { public class CustomerDto : IBaseDto, ICustomer { + [Key] public string CustomerId { get; set; } [Required] diff --git a/NorthwindCRUD/Models/Dtos/EmployeeDto.cs b/NorthwindCRUD/Models/Dtos/EmployeeDto.cs index a534f69..8952600 100644 --- a/NorthwindCRUD/Models/Dtos/EmployeeDto.cs +++ b/NorthwindCRUD/Models/Dtos/EmployeeDto.cs @@ -6,6 +6,7 @@ namespace NorthwindCRUD.Models.Dtos { public class EmployeeDto : IBaseDto, IEmployee { + [Key] [SwaggerSchema("Number automatically assigned to new employee.")] [Required] public int EmployeeId { get; set; } @@ -28,8 +29,6 @@ public class EmployeeDto : IBaseDto, IEmployee [SwaggerSchema("Employee's hire date", Format = "date")] public string HireDate { get; set; } - public string AddressId { get; set; } - public AddressDto Address { get; set; } [SwaggerSchema("General information about employee's background.")] diff --git a/NorthwindCRUD/Models/Dtos/EmployeeTerritoryDto.cs b/NorthwindCRUD/Models/Dtos/EmployeeTerritoryDto.cs index 5a890cf..fc805b8 100644 --- a/NorthwindCRUD/Models/Dtos/EmployeeTerritoryDto.cs +++ b/NorthwindCRUD/Models/Dtos/EmployeeTerritoryDto.cs @@ -1,9 +1,11 @@ +using System.ComponentModel.DataAnnotations; using NorthwindCRUD.Models.Contracts; namespace NorthwindCRUD.Models.Dtos { public class EmployeeTerritoryDto : IBaseDto, IEmployeeTerritory { + [Key] public int EmployeeId { get; set; } public string TerritoryId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/OrderDto.cs b/NorthwindCRUD/Models/Dtos/OrderDto.cs index 1097371..7fe9b4c 100644 --- a/NorthwindCRUD/Models/Dtos/OrderDto.cs +++ b/NorthwindCRUD/Models/Dtos/OrderDto.cs @@ -1,9 +1,11 @@ namespace NorthwindCRUD.Models.Dtos { + using System.ComponentModel.DataAnnotations; using NorthwindCRUD.Models.Contracts; public class OrderDto : IBaseDto, IOrder { + [Key] public int OrderId { get; set; } public string CustomerId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/ProductDto.cs b/NorthwindCRUD/Models/Dtos/ProductDto.cs index 57c2ad8..d49da44 100644 --- a/NorthwindCRUD/Models/Dtos/ProductDto.cs +++ b/NorthwindCRUD/Models/Dtos/ProductDto.cs @@ -1,9 +1,11 @@ -using NorthwindCRUD.Models.Contracts; +using System.ComponentModel.DataAnnotations; +using NorthwindCRUD.Models.Contracts; namespace NorthwindCRUD.Models.Dtos { public class ProductDto : IBaseDto, IProduct { + [Key] public int ProductId { get; set; } public int? SupplierId { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/RegionDto.cs b/NorthwindCRUD/Models/Dtos/RegionDto.cs index 27e05a3..affa89a 100644 --- a/NorthwindCRUD/Models/Dtos/RegionDto.cs +++ b/NorthwindCRUD/Models/Dtos/RegionDto.cs @@ -1,9 +1,11 @@ -using NorthwindCRUD.Models.Contracts; +using System.ComponentModel.DataAnnotations; +using NorthwindCRUD.Models.Contracts; namespace NorthwindCRUD.Models.Dtos { public class RegionDto : IBaseDto, IRegion { + [Key] public int RegionId { get; set; } public string RegionDescription { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/ShipperDto.cs b/NorthwindCRUD/Models/Dtos/ShipperDto.cs index bad3862..508f070 100644 --- a/NorthwindCRUD/Models/Dtos/ShipperDto.cs +++ b/NorthwindCRUD/Models/Dtos/ShipperDto.cs @@ -1,9 +1,11 @@ -using NorthwindCRUD.Models.Contracts; +using System.ComponentModel.DataAnnotations; +using NorthwindCRUD.Models.Contracts; namespace NorthwindCRUD.Models.Dtos { public class ShipperDto : IBaseDto, IShipper { + [Key] public int ShipperId { get; set; } public string CompanyName { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/SupplierDto.cs b/NorthwindCRUD/Models/Dtos/SupplierDto.cs index 1e3e577..e99f9e0 100644 --- a/NorthwindCRUD/Models/Dtos/SupplierDto.cs +++ b/NorthwindCRUD/Models/Dtos/SupplierDto.cs @@ -1,9 +1,11 @@ -using NorthwindCRUD.Models.Contracts; +using System.ComponentModel.DataAnnotations; +using NorthwindCRUD.Models.Contracts; namespace NorthwindCRUD.Models.Dtos { public class SupplierDto : IBaseDto, ISupplier { + [Key] public int SupplierId { get; set; } public string? CompanyName { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/TerritoryDto.cs b/NorthwindCRUD/Models/Dtos/TerritoryDto.cs index 22f0b72..2846e6d 100644 --- a/NorthwindCRUD/Models/Dtos/TerritoryDto.cs +++ b/NorthwindCRUD/Models/Dtos/TerritoryDto.cs @@ -1,9 +1,11 @@ -using NorthwindCRUD.Models.Contracts; +using System.ComponentModel.DataAnnotations; +using NorthwindCRUD.Models.Contracts; namespace NorthwindCRUD.Models.Dtos { public class TerritoryDto : IBaseDto, ITerritory { + [Key] public string TerritoryId { get; set; } public string TerritoryDescription { get; set; } diff --git a/NorthwindCRUD/Services/BaseDbService.cs b/NorthwindCRUD/Services/BaseDbService.cs index 7b5abf8..caa33b8 100644 --- a/NorthwindCRUD/Services/BaseDbService.cs +++ b/NorthwindCRUD/Services/BaseDbService.cs @@ -1,17 +1,18 @@ using System.ComponentModel.DataAnnotations; using AutoMapper; using Microsoft.EntityFrameworkCore; +using NorthwindCRUD.Helpers; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { public abstract class BaseDbService - where TDto : class, IBaseDto - where TDb : class, IBaseDb, new() + where TDto : class, IBaseDto + where TDb : class, IBaseDb, new() { - private readonly DataContext dataContext; - private readonly IMapper mapper; + protected readonly DataContext dataContext; + protected readonly IMapper mapper; private readonly IPagingService pagingService; public BaseDbService(DataContext dataContext, IMapper mapper, IPagingService pagingService) @@ -61,7 +62,7 @@ public IQueryable GetAllAsQueryable() return mapper.Map(dbResult); } - private TDb GetDbById(TId id) + protected TDb GetDbById(TId id) { TDb dtoInstance = new TDb(); @@ -76,7 +77,7 @@ private TDb GetDbById(TId id) if (keyProperty == null) { - throw new Exception("No key property found on entity"); + throw new InvalidOperationException("No key property found on entity"); } TDb? dbResult = query.FirstOrDefault(entity => @@ -94,47 +95,66 @@ public PagedResultDto GetWithPageSkip(int? skip = null, int? top = null, i return pagedResult; } - public async Task Upsert(TDto model) + public async Task Update(TDto model) + { + var keyProperty = typeof(TDto).GetProperties() + .FirstOrDefault(p => Attribute.IsDefined(p, typeof(KeyAttribute))); + + if (keyProperty == null) + { + throw new InvalidOperationException("No key property found on entity"); + } + + var keyValue = (TId)keyProperty.GetValue(model); + + return await Update(model, keyValue); + } + + public async Task Update(TDto model, TId id) { if (model == null) { throw new ArgumentNullException(nameof(model)); } - // Find the key property using reflection (assumes you have a KeyAttribute defined) - var keyProperty = typeof(TDb).GetProperties() - .FirstOrDefault(p => Attribute.IsDefined(p, typeof(KeyAttribute))); + var dbModel = mapper.Map(model); - if (keyProperty == null) + var existingEntity = GetDbById(id); + if (existingEntity == null) { - throw new InvalidOperationException($"Entity {typeof(TDb).Name} has no key property defined."); + throw new KeyNotFoundException($"Entity with id {id} not found."); } - // Assuming your DTO has a property named "Id" that corresponds to the primary key - var dtoId = (int?)keyProperty.GetValue(model); + //todo improve + mapper.Map(dbModel, existingEntity, opts => opts.Items["IsPatch"] = true); + + await dataContext.SaveChangesAsync(); + var mappedResult = mapper.Map(existingEntity); + return mappedResult; + } - if (model == null || dtoId == 0) + public async Task Create(TDto model) + { + if (model == null) { - // New entity (insert) - var newEntity = mapper.Map(model); - await dataContext.Set().AddAsync(newEntity); - await dataContext.SaveChangesAsync(); - var mappedResult = mapper.Map(newEntity); - return mappedResult; + throw new ArgumentNullException(nameof(model)); } - else + + var dbModel = mapper.Map(model); + + var keyProperty = typeof(TDb).GetProperties() + .FirstOrDefault(p => Attribute.IsDefined(p, typeof(KeyAttribute))); + + if (keyProperty != null && typeof(TId) == typeof(int)) { - var existingEntity = await dataContext.Set().FindAsync(dtoId); - if (existingEntity == null) - { - throw new Exception($"Entity with id {dtoId} not found."); - } - - mapper.Map(model, existingEntity, opts => opts.Items["IsPatch"] = true); - await dataContext.SaveChangesAsync(); - var mappedResult = mapper.Map(existingEntity); - return mappedResult; + keyProperty.SetValue(dbModel, 0); } + + PropertyHelper.MakePropertiesEmptyIfNull(dbModel); + var addedEntity = await dataContext.Set().AddAsync(dbModel); + await dataContext.SaveChangesAsync(); + var mappedResult = mapper.Map(dbModel); + return mappedResult; } public CountResultDto GetCount() diff --git a/NorthwindCRUD/Services/CategoryService.cs b/NorthwindCRUD/Services/CategoryService.cs index 84e5934..af35a3f 100644 --- a/NorthwindCRUD/Services/CategoryService.cs +++ b/NorthwindCRUD/Services/CategoryService.cs @@ -1,39 +1,20 @@ namespace NorthwindCRUD.Services { using AutoMapper; - using NorthwindCRUD.Helpers; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; - public class CategoryService : BaseDbService + public class CategoryService : BaseDbService { - private readonly DataContext dataContext; - private readonly IPagingService pagingService; - public CategoryService(DataContext dataContext, IPagingService pagingService, IMapper mapper) : base(dataContext, mapper, pagingService) { - this.dataContext = dataContext; } - public CategoryDb Create(CategoryDb model) + public CategoryDetailsDto GetDetailsById(int id) { - var id = IdGenerator.CreateDigitsId(); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateDigitsId(); - existWithId = this.GetById(id); - } - - model.CategoryId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - var categoryEntity = this.dataContext.Categories.Add(model); - this.dataContext.SaveChanges(); - - return categoryEntity.Entity; + var category = this.GetDbById(id); + return this.mapper.Map(category); } } } diff --git a/NorthwindCRUD/Services/CustomerService.cs b/NorthwindCRUD/Services/CustomerService.cs index 5d600d4..2683399 100644 --- a/NorthwindCRUD/Services/CustomerService.cs +++ b/NorthwindCRUD/Services/CustomerService.cs @@ -6,7 +6,7 @@ namespace NorthwindCRUD.Services { public class CustomerService : BaseDbService { - public CustomerService(DataContext dataContext, IMapper mapper, IPagingService pagingService) + public CustomerService(DataContext dataContext, IPagingService pagingService, IMapper mapper) : base(dataContext, mapper, pagingService) { } } } diff --git a/NorthwindCRUD/Services/EmployeeService.cs b/NorthwindCRUD/Services/EmployeeService.cs index 52d7c38..cd134fb 100644 --- a/NorthwindCRUD/Services/EmployeeService.cs +++ b/NorthwindCRUD/Services/EmployeeService.cs @@ -1,124 +1,21 @@ namespace NorthwindCRUD.Services { - using Microsoft.EntityFrameworkCore; - using NorthwindCRUD.Helpers; + using AutoMapper; using NorthwindCRUD.Models.DbModels; + using NorthwindCRUD.Models.Dtos; - public class EmployeeService + public class EmployeeService : BaseDbService { - private readonly DataContext dataContext; - - public EmployeeService(DataContext dataContext) - { - this.dataContext = dataContext; - } - - public EmployeeDb[] GetAll() + public EmployeeService(DataContext dataContext, IPagingService pagingService, IMapper mapper) + : base(dataContext, mapper, pagingService) { - return this.dataContext.Employees - .Include(c => c.Address) - .ToArray(); } - public IQueryable GetAllAsQueryable() + public EmployeeDto[] GetEmployeesByReportsTo(int id) { - return this.dataContext.Employees; - } - - public EmployeeDb? GetById(int id) - { - return this.dataContext.Employees.FirstOrDefault(c => c.EmployeeId == id); - } - - public EmployeeDb[] GetEmployeesByReportsTo(int id) - { - return this.dataContext.Employees + return mapper.Map(this.dataContext.Employees .Where(c => c.ReportsTo == id) - .ToArray(); - } - - public EmployeeDb Create(EmployeeDb model) - { - var id = IdGenerator.CreateDigitsId(); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateDigitsId(); - existWithId = this.GetById(id); - } - - model.EmployeeId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - if (model.Address == null) - { - var emptyAddress = this.dataContext.Addresses.FirstOrDefault(a => a.Street == string.Empty); - if (emptyAddress != null) - { - model.Address = emptyAddress; - model.AddressId = emptyAddress.AddressId; - } - } - - var employeeEntity = this.dataContext.Employees.Add(model); - this.dataContext.SaveChanges(); - - return employeeEntity.Entity; - } - - public EmployeeDb? Update(EmployeeDb model) - { - var employeeEntity = this.dataContext.Employees - .Include(c => c.Address) - .FirstOrDefault(e => e.EmployeeId == model.EmployeeId); - - if (employeeEntity != null) - { - employeeEntity.LastName = model.LastName != null ? model.LastName : employeeEntity.LastName; - employeeEntity.FirstName = model.FirstName != null ? model.FirstName : employeeEntity.FirstName; - employeeEntity.Title = model.Title != null ? model.Title : employeeEntity.Title; - employeeEntity.TitleOfCourtesy = model.TitleOfCourtesy != null ? model.TitleOfCourtesy : employeeEntity.TitleOfCourtesy; - employeeEntity.BirthDate = model.BirthDate != null ? model.BirthDate : employeeEntity.BirthDate; - employeeEntity.HireDate = model.HireDate != null ? model.HireDate : employeeEntity.HireDate; - employeeEntity.Notes = model.Notes != null ? model.Notes : employeeEntity.Notes; - employeeEntity.AvatarUrl = model.AvatarUrl != null ? model.AvatarUrl : employeeEntity.AvatarUrl; - - if (model.Address != null) - { - var newAddress = this.dataContext.Addresses.FirstOrDefault(a => a.Street == model.Address.Street); - if (newAddress != null) - { - employeeEntity.Address.City = model.Address.City != null ? model.Address.City : employeeEntity.Address.City; - employeeEntity.Address.Region = model.Address.Region != null ? model.Address.Region : employeeEntity.Address.Region; - employeeEntity.Address.PostalCode = model.Address.PostalCode != null ? model.Address.PostalCode : employeeEntity.Address.PostalCode; - employeeEntity.Address.Country = model.Address.Country != null ? model.Address.Country : employeeEntity.Address.Country; - employeeEntity.Address.Phone = model.Address.Phone != null ? model.Address.Phone : employeeEntity.Address.Phone; - } - else - { - var employeeNewAddress = this.dataContext.Addresses.Add(model.Address); - employeeEntity.Address = employeeNewAddress.Entity; - employeeEntity.AddressId = employeeNewAddress.Entity.AddressId; - } - } - - this.dataContext.SaveChanges(); - } - - return employeeEntity; - } - - public EmployeeDb? Delete(int id) - { - var employeeEntity = this.GetById(id); - if (employeeEntity != null) - { - this.dataContext.Employees.Remove(employeeEntity); - this.dataContext.SaveChanges(); - } - - return employeeEntity; + .ToArray()); } } } diff --git a/NorthwindCRUD/Services/EmployeeTerritoryService.cs b/NorthwindCRUD/Services/EmployeeTerritoryService.cs index 04135b8..774aaab 100644 --- a/NorthwindCRUD/Services/EmployeeTerritoryService.cs +++ b/NorthwindCRUD/Services/EmployeeTerritoryService.cs @@ -1,21 +1,25 @@ using System.Globalization; +using AutoMapper; using Microsoft.EntityFrameworkCore; using NorthwindCRUD.Constants; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { public class EmployeeTerritoryService { private readonly DataContext dataContext; + private readonly IMapper mapper; - public EmployeeTerritoryService(DataContext dataContext) + public EmployeeTerritoryService(DataContext dataContext, IMapper mapper) { this.dataContext = dataContext; + this.mapper = mapper; } [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1011:Closing square brackets should be spaced correctly", Justification = "Need to return nullable type")] - public EmployeeDb[]? GetEmployeesByTerritoryId(string id) + public EmployeeDto[]? GetEmployeesByTerritoryId(string id) { var territory = this.dataContext.Territories .Include(t => t.EmployeesTerritories) @@ -24,14 +28,15 @@ public EmployeeTerritoryService(DataContext dataContext) if (territory != null) { - return territory.EmployeesTerritories.Select(et => et.Employee).ToArray(); + var employees = territory.EmployeesTerritories.Select(et => et.Employee).ToArray(); + return mapper.Map(employees); } return null; } [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1011:Closing square brackets should be spaced correctly", Justification = "Need to return nullable type")] - public TerritoryDb[]? GetTeritoriesByEmployeeId(int id) + public TerritoryDto[]? GetTeritoriesByEmployeeId(int id) { var employee = this.dataContext.Employees .Include(c => c.Address) @@ -41,22 +46,23 @@ public EmployeeTerritoryService(DataContext dataContext) if (employee != null) { - return employee.EmployeesTerritories.Select(et => et.Territory).ToArray(); + var territories = employee.EmployeesTerritories.Select(et => et.Territory).ToArray(); + return mapper.Map(territories); } return null; } - public EmployeeTerritoryDb AddTerritoryToEmployee(EmployeeTerritoryDb model) + public EmployeeTerritoryDto AddTerritoryToEmployee(EmployeeTerritoryDto model) { if (this.dataContext.Employees.FirstOrDefault(e => e.EmployeeId == model.EmployeeId) == null) { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Employee), model.EmployeeId.ToString(CultureInfo.InvariantCulture))); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.EmployeeId), model.EmployeeId.ToString(CultureInfo.InvariantCulture))); } if (this.dataContext.Territories.FirstOrDefault(t => t.TerritoryId == model.TerritoryId) == null) { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Territory), model.TerritoryId.ToString())); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.TerritoryId), model.TerritoryId.ToString())); } var employeeTerritory = new EmployeeTerritoryDb @@ -68,7 +74,7 @@ public EmployeeTerritoryDb AddTerritoryToEmployee(EmployeeTerritoryDb model) dataContext.EmployeesTerritories.Add(employeeTerritory); dataContext.SaveChanges(); - return employeeTerritory; + return mapper.Map(employeeTerritory); } } } diff --git a/NorthwindCRUD/Services/OrderService.cs b/NorthwindCRUD/Services/OrderService.cs index 431fbbd..cf343e9 100644 --- a/NorthwindCRUD/Services/OrderService.cs +++ b/NorthwindCRUD/Services/OrderService.cs @@ -1,200 +1,66 @@ -using System.Globalization; -using AutoMapper; +using AutoMapper; using Microsoft.CodeAnalysis; using Microsoft.EntityFrameworkCore; -using NorthwindCRUD.Constants; -using NorthwindCRUD.Helpers; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { - public class OrderService + public class OrderService : BaseDbService { - private readonly DataContext dataContext; - private readonly IMapper mapper; - - public OrderService(DataContext dataContext, IMapper mapper) + public OrderService(DataContext dataContext, IPagingService pagingService, IMapper mapper) + : base(dataContext, mapper, pagingService) { - this.dataContext = dataContext; - this.mapper = mapper; } - public OrderDb[] GetAll() + public OrderDto[] GetNOrders(int numberOfOrdersToRetrieve) { - return this.dataContext.Orders - .Include(c => c.ShipAddress) - .ToArray(); - } - - public IQueryable GetAllAsQueryable() - { - return this.dataContext.Orders; - } - - public OrderDb[] GetNOrders(int numberOfOrdersToRetrieve) - { - return this.dataContext.Orders + var oreders = this.dataContext.Orders .Include(c => c.ShipAddress) .Take(numberOfOrdersToRetrieve) .ToArray(); - } - public OrderDb? GetById(int id) - { - return GetOrdersQuery().FirstOrDefault(c => c.OrderId == id); + return this.mapper.Map(oreders); } - public OrderDetailDb[] GetOrderDetailsById(int id) + public OrderDetailDto[] GetOrderDetailsById(int id) { var details = this.dataContext.OrderDetails.Where(o => o.OrderId == id).ToArray(); - return details; + return this.mapper.Map(details); } public OrderDto[] GetOrdersByCustomerId(string id) { - return mapper.Map(GetOrdersQuery() + return mapper.Map(this.GetAllAsQueryable() .Where(o => o.CustomerId == id) .ToArray()); } - public OrderDb[] GetOrdersByEmployeeId(int id) + public OrderDto[] GetOrdersByEmployeeId(int id) { - return GetOrdersQuery() + var oders = this.GetAllAsQueryable() .Where(o => o.EmployeeId == id) .ToArray(); + + return this.mapper.Map(oders); } - public OrderDb[] GetOrdersByShipperId(int id) + public OrderDto[] GetOrdersByShipperId(int id) { - return GetOrdersQuery() + var oreders = this.GetAllAsQueryable() .Where(o => o.ShipVia == id) .ToArray(); + + return this.mapper.Map(oreders); } - public OrderDetailDb[] GetOrderDetailsByProductId(int id) + public OrderDetailDto[] GetOrderDetailsByProductId(int id) { var details = this.dataContext.OrderDetails .Where(o => o.ProductId == id) .ToArray(); - return details; - } - - public OrderDb Create(OrderDb model) - { - if (this.dataContext.Customers.FirstOrDefault(c => c.CustomerId == model.CustomerId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Customer), model.CustomerId?.ToString(CultureInfo.InvariantCulture))); - } - - if (this.dataContext.Employees.FirstOrDefault(e => e.EmployeeId == model.EmployeeId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Employee), model.EmployeeId?.ToString(CultureInfo.InvariantCulture))); - } - - if (this.dataContext.Shippers.FirstOrDefault(s => s.ShipperId == model.ShipperId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Shipper), model.ShipperId?.ToString(CultureInfo.InvariantCulture))); - } - - var id = IdGenerator.CreateDigitsId(); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateDigitsId(); - existWithId = this.GetById(id); - } - - model.OrderId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - if (model.ShipAddress == null) - { - var emptyAddress = this.dataContext.Addresses.FirstOrDefault(a => a.Street == string.Empty); - model.ShipAddress = emptyAddress; - model.ShipAddressId = emptyAddress?.AddressId; - } - - var orderEntity = this.dataContext.Orders.Add(model); - this.dataContext.SaveChanges(); - - return orderEntity.Entity; - } - - public OrderDb? Update(OrderDb model) - { - if (this.dataContext.Customers.FirstOrDefault(c => c.CustomerId == model.CustomerId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Customer), model.CustomerId?.ToString())); - } - - if (this.dataContext.Employees.FirstOrDefault(e => e.EmployeeId == model.EmployeeId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Employee), model.EmployeeId?.ToString(CultureInfo.InvariantCulture))); - } - - if (this.dataContext.Shippers.FirstOrDefault(s => s.ShipperId == model.ShipperId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Shipper), model.ShipperId?.ToString(CultureInfo.InvariantCulture))); - } - - var orderEntity = this.dataContext.Orders - .Include(c => c.ShipAddress) - .FirstOrDefault(e => e.OrderId == model.OrderId); - - if (orderEntity != null) - { - orderEntity.OrderDate = model.OrderDate != null ? model.OrderDate : orderEntity.OrderDate; - orderEntity.RequiredDate = model.RequiredDate != null ? model.RequiredDate : orderEntity.RequiredDate; - orderEntity.ShipVia = model.ShipVia; // ShipVia has int type which can't be null - orderEntity.Freight = model.Freight; // Freight has double type which can't be null - orderEntity.ShipName = model.ShipName != null ? model.ShipName : orderEntity.ShipName; - orderEntity.EmployeeId = model.EmployeeId != null ? model.EmployeeId : orderEntity.EmployeeId; - orderEntity.CustomerId = model.CustomerId != null ? model.CustomerId : orderEntity.CustomerId; - - if (model.ShipAddress != null) - { - var newAddress = this.dataContext.Addresses.FirstOrDefault(a => a.Street == model.ShipAddress.Street); - if (newAddress != null && orderEntity.ShipAddress != null) - { - orderEntity.ShipAddress.City = model.ShipAddress.City; - orderEntity.ShipAddress.Region = model.ShipAddress.Region; - orderEntity.ShipAddress.PostalCode = model.ShipAddress.PostalCode; - orderEntity.ShipAddress.Country = model.ShipAddress.Country; - orderEntity.ShipAddress.Phone = model.ShipAddress.Phone; - } - else - { - var employeeNewAddress = this.dataContext.Addresses.Add(model.ShipAddress); - orderEntity.ShipAddress = employeeNewAddress.Entity; - orderEntity.ShipAddressId = employeeNewAddress.Entity.AddressId; - } - } - - this.dataContext.SaveChanges(); - } - - return orderEntity; - } - - public OrderDb? Delete(int id) - { - var orderEntity = this.GetById(id); - if (orderEntity != null) - { - this.dataContext.Orders.Remove(orderEntity); - this.dataContext.SaveChanges(); - } - - return orderEntity; - } - - private IQueryable GetOrdersQuery() - { - return this.dataContext.Orders - .Include(c => c.ShipAddress); + return this.mapper.Map(details); } } } diff --git a/NorthwindCRUD/Services/ProductService.cs b/NorthwindCRUD/Services/ProductService.cs index 32089bb..e3acf27 100644 --- a/NorthwindCRUD/Services/ProductService.cs +++ b/NorthwindCRUD/Services/ProductService.cs @@ -1,121 +1,33 @@ -using System.Globalization; -using NorthwindCRUD.Constants; -using NorthwindCRUD.Helpers; +using AutoMapper; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { - public class ProductService + public class ProductService : BaseDbService { - private readonly DataContext dataContext; - public ProductService(DataContext dataContext) + public ProductService(DataContext dataContext, IPagingService pagingService, IMapper mapper) + : base(dataContext, mapper, pagingService) { - this.dataContext = dataContext; } - public ProductDb[] GetAll() + public ProductDto[] GetAllByCategoryId(int id) { - return this.dataContext.Products.ToArray(); + var products = this.dataContext.Products.Where(p => p.CategoryId == id).ToArray(); + return mapper.Map(products); } - public IQueryable GetAllAsQueryable() + public ProductDto[] GetAllBySupplierId(int id) { - return this.dataContext.Products; + var products = this.dataContext.Products.Where(p => p.SupplierId == id).ToArray(); + return mapper.Map(products); } - public ProductDb? GetById(int id) + public ProductDto[] GetProductsByIds(int[] productIds) { - return this.dataContext.Products.FirstOrDefault(p => p.ProductId == id); - } - - public ProductDb[] GetAllByCategoryId(int id) - { - return this.dataContext.Products.Where(p => p.CategoryId == id).ToArray(); - } - - public ProductDb[] GetAllBySupplierId(int id) - { - return this.dataContext.Products.Where(p => p.SupplierId == id).ToArray(); - } - - public ProductDb[] GetProductsByIds(int[] productIds) - { - return this.dataContext.Products - .Where(p => productIds.Contains(p.ProductId)) - .ToArray(); - } - - public ProductDb Create(ProductDb model) - { - if (this.dataContext.Categories.FirstOrDefault(c => c.CategoryId == model.CategoryId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Category), model.CategoryId?.ToString(CultureInfo.InvariantCulture))); - } - - if (this.dataContext.Suppliers.FirstOrDefault(s => s.SupplierId == model.SupplierId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Supplier), model.SupplierId?.ToString(CultureInfo.InvariantCulture))); - } - - var id = IdGenerator.CreateDigitsId(); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateDigitsId(); - existWithId = this.GetById(id); - } - - model.ProductId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - var productEntity = this.dataContext.Products.Add(model); - this.dataContext.SaveChanges(); - - return productEntity.Entity; - } - - public ProductDb? Update(ProductDb model) - { - if (this.dataContext.Categories.FirstOrDefault(c => c.CategoryId == model.CategoryId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Category), model.CategoryId?.ToString(CultureInfo.InvariantCulture))); - } - - if (this.dataContext.Suppliers.FirstOrDefault(s => s.SupplierId == model.SupplierId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Supplier), model.SupplierId?.ToString(CultureInfo.InvariantCulture))); - } - - var productEntity = this.dataContext.Products.FirstOrDefault(p => p.ProductId == model.ProductId); - if (productEntity != null) - { - productEntity.SupplierId = model.SupplierId != null ? model.SupplierId : productEntity.SupplierId; - productEntity.CategoryId = model.CategoryId != null ? model.CategoryId : productEntity.CategoryId; - productEntity.QuantityPerUnit = model.QuantityPerUnit != null ? model.QuantityPerUnit : productEntity.QuantityPerUnit; - productEntity.UnitPrice = model.UnitPrice != null ? model.UnitPrice : productEntity.UnitPrice; - productEntity.UnitsInStock = model.UnitsInStock != null ? model.UnitsInStock : productEntity.UnitsInStock; - productEntity.UnitsOnOrder = model.UnitsOnOrder != null ? model.UnitsOnOrder : productEntity.UnitsOnOrder; - productEntity.ReorderLevel = model.ReorderLevel != null ? model.ReorderLevel : productEntity.ReorderLevel; - productEntity.Discontinued = model.Discontinued != productEntity.Discontinued ? model.Discontinued : productEntity.Discontinued; - - this.dataContext.SaveChanges(); - } - - return productEntity; - } - - public ProductDb? Delete(int id) - { - var productEntity = this.GetById(id); - if (productEntity != null) - { - this.dataContext.Products.Remove(productEntity); - this.dataContext.SaveChanges(); - } - - return productEntity; + var products = this.dataContext.Products.Where(p => productIds.Contains(p.ProductId)).ToArray(); + return mapper.Map(products); } } } diff --git a/NorthwindCRUD/Services/RegionService.cs b/NorthwindCRUD/Services/RegionService.cs index 2f5d6d7..0c974bf 100644 --- a/NorthwindCRUD/Services/RegionService.cs +++ b/NorthwindCRUD/Services/RegionService.cs @@ -1,75 +1,15 @@ -using NorthwindCRUD.Helpers; +using AutoMapper; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { - public class RegionService + public class RegionService : BaseDbService { - private readonly DataContext dataContext; - public RegionService(DataContext dataContext) + public RegionService(DataContext dataContext, IPagingService pagingService, IMapper mapper) + : base(dataContext, mapper, pagingService) { - this.dataContext = dataContext; - } - - public RegionDb[] GetAll() - { - return this.dataContext.Regions.ToArray(); - } - - public IQueryable GetAllAsQueryable() - { - return this.dataContext.Regions; - } - - public RegionDb? GetById(int id) - { - return this.dataContext.Regions.FirstOrDefault(p => p.RegionId == id); - } - - public RegionDb Create(RegionDb model) - { - var id = IdGenerator.CreateDigitsId(); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateDigitsId(); - existWithId = this.GetById(id); - } - - model.RegionId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - var regionEntity = this.dataContext.Regions.Add(model); - this.dataContext.SaveChanges(); - - return regionEntity.Entity; - } - - public RegionDb? Update(RegionDb model) - { - var regionEntity = this.dataContext.Regions.FirstOrDefault(p => p.RegionId == model.RegionId); - if (regionEntity != null) - { - regionEntity.RegionDescription = model.RegionDescription != null ? model.RegionDescription : regionEntity.RegionDescription; - - this.dataContext.SaveChanges(); - } - - return regionEntity; - } - - public RegionDb? Delete(int id) - { - var regionEntity = this.GetById(id); - if (regionEntity != null) - { - this.dataContext.Regions.Remove(regionEntity); - this.dataContext.SaveChanges(); - } - - return regionEntity; } } } diff --git a/NorthwindCRUD/Services/SalesService.cs b/NorthwindCRUD/Services/SalesService.cs index 8f0dffc..ebd072f 100644 --- a/NorthwindCRUD/Services/SalesService.cs +++ b/NorthwindCRUD/Services/SalesService.cs @@ -88,7 +88,7 @@ public SalesDto[] RetrieveSalesDataByYear(int year, int? startMonth, int? endMon { if (year == 0) { - throw new ArgumentException("Year is required.", nameof(year)); + throw new ArgumentException("Year is required.", nameof(year)); } var salesData = this.dataContext.OrderDetails diff --git a/NorthwindCRUD/Services/ShipperService.cs b/NorthwindCRUD/Services/ShipperService.cs index b9143f2..b6fc4a6 100644 --- a/NorthwindCRUD/Services/ShipperService.cs +++ b/NorthwindCRUD/Services/ShipperService.cs @@ -1,76 +1,14 @@ -using NorthwindCRUD.Helpers; +using AutoMapper; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { - public class ShipperService + public class ShipperService : BaseDbService { - private readonly DataContext dataContext; - - public ShipperService(DataContext dataContext) - { - this.dataContext = dataContext; - } - - public ShipperDb[] GetAll() - { - return this.dataContext.Shippers.ToArray(); - } - - public IQueryable GetAllAsQueryable() - { - return this.dataContext.Shippers; - } - - public ShipperDb? GetById(int id) - { - return this.dataContext.Shippers.FirstOrDefault(p => p.ShipperId == id); - } - - public ShipperDb Create(ShipperDb model) + public ShipperService(DataContext dataContext, IPagingService pagingService, IMapper mapper) + : base(dataContext, mapper, pagingService) { - var id = IdGenerator.CreateDigitsId(); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateDigitsId(); - existWithId = this.GetById(id); - } - - model.ShipperId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - var shipperEntity = this.dataContext.Shippers.Add(model); - this.dataContext.SaveChanges(); - - return shipperEntity.Entity; - } - - public ShipperDb? Update(ShipperDb model) - { - var shipperEntity = this.dataContext.Shippers.FirstOrDefault(p => p.ShipperId == model.ShipperId); - if (shipperEntity != null) - { - shipperEntity.Phone = model.Phone != null ? model.Phone : shipperEntity.Phone; - shipperEntity.CompanyName = model.CompanyName != null ? model.CompanyName : shipperEntity.CompanyName; - - this.dataContext.SaveChanges(); - } - - return shipperEntity; - } - - public ShipperDb? Delete(int id) - { - var shipperEntity = this.GetById(id); - if (shipperEntity != null) - { - this.dataContext.Shippers.Remove(shipperEntity); - this.dataContext.SaveChanges(); - } - - return shipperEntity; } } } diff --git a/NorthwindCRUD/Services/SupplierService.cs b/NorthwindCRUD/Services/SupplierService.cs index e7a852e..ac7d7ec 100644 --- a/NorthwindCRUD/Services/SupplierService.cs +++ b/NorthwindCRUD/Services/SupplierService.cs @@ -1,85 +1,14 @@ -using NorthwindCRUD.Helpers; +using AutoMapper; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { - public class SupplierService + public class SupplierService : BaseDbService { - private readonly DataContext dataContext; - - public SupplierService(DataContext dataContext) - { - this.dataContext = dataContext; - } - - public SupplierDb[] GetAll() - { - return this.dataContext.Suppliers.ToArray(); - } - - public IQueryable GetAllAsQueryable() - { - return this.dataContext.Suppliers; - } - - public SupplierDb? GetById(int id) - { - return this.dataContext.Suppliers.FirstOrDefault(p => p.SupplierId == id); - } - - public SupplierDb Create(SupplierDb model) + public SupplierService(DataContext dataContext, IPagingService pagingService, IMapper mapper) + : base(dataContext, mapper, pagingService) { - var id = IdGenerator.CreateDigitsId(); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateDigitsId(); - existWithId = this.GetById(id); - } - - model.SupplierId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - var supplierEntity = this.dataContext.Suppliers.Add(model); - this.dataContext.SaveChanges(); - - return supplierEntity.Entity; - } - - public SupplierDb? Update(SupplierDb model) - { - var supplierEntity = this.dataContext.Suppliers.FirstOrDefault(p => p.SupplierId == model.SupplierId); - if (supplierEntity != null) - { - supplierEntity.Address = model.Address != null ? model.Address : supplierEntity.Address; - supplierEntity.City = model.City != null ? model.City : supplierEntity.City; - supplierEntity.Fax = model.Fax != null ? model.Fax : supplierEntity.Fax; - supplierEntity.CompanyName = model.CompanyName != null ? model.CompanyName : supplierEntity.CompanyName; - supplierEntity.ContactName = model.ContactName != null ? model.ContactName : supplierEntity.ContactName; - supplierEntity.ContactTitle = model.ContactTitle != null ? model.ContactTitle : supplierEntity.ContactTitle; - supplierEntity.Country = model.Country != null ? model.Country : supplierEntity.Country; - supplierEntity.HomePage = model.HomePage != null ? model.HomePage : supplierEntity.HomePage; - supplierEntity.Phone = model.Phone != null ? model.Phone : supplierEntity.Phone; - supplierEntity.PostalCode = model.PostalCode != null ? model.PostalCode : supplierEntity.PostalCode; - supplierEntity.Region = model.Region != null ? model.Region : supplierEntity.Region; - - this.dataContext.SaveChanges(); - } - - return supplierEntity; - } - - public SupplierDb? Delete(int id) - { - var supplierEntity = this.GetById(id); - if (supplierEntity != null) - { - this.dataContext.Suppliers.Remove(supplierEntity); - this.dataContext.SaveChanges(); - } - - return supplierEntity; } } } diff --git a/NorthwindCRUD/Services/TerritoryService.cs b/NorthwindCRUD/Services/TerritoryService.cs index 5f5c799..01e6059 100644 --- a/NorthwindCRUD/Services/TerritoryService.cs +++ b/NorthwindCRUD/Services/TerritoryService.cs @@ -1,93 +1,21 @@ -using System.Globalization; -using NorthwindCRUD.Constants; -using NorthwindCRUD.Helpers; +using AutoMapper; using NorthwindCRUD.Models.DbModels; +using NorthwindCRUD.Models.Dtos; namespace NorthwindCRUD.Services { - public class TerritoryService + public class TerritoryService : BaseDbService { - private readonly DataContext dataContext; - public TerritoryService(DataContext dataContext) + public TerritoryService(DataContext dataContext, IPagingService pagingService, IMapper mapper) + : base(dataContext, mapper, pagingService) { - this.dataContext = dataContext; } - public TerritoryDb[] GetAll() + public TerritoryDto[] GetTerritoriesByRegionId(int id) { - return this.dataContext.Territories.ToArray(); - } - - public IQueryable GetAllAsQueryable() - { - return this.dataContext.Territories; - } - - public TerritoryDb? GetById(string id) - { - return this.dataContext.Territories.FirstOrDefault(t => t.TerritoryId == id); - } - - public TerritoryDb[] GetTerritoriesByRegionId(int id) - { - return this.dataContext.Territories.Where(t => t.RegionId == id).ToArray(); - } - - public TerritoryDb Create(TerritoryDb model) - { - if (this.dataContext.Regions.FirstOrDefault(r => r.RegionId == model.RegionId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Region), model.RegionId?.ToString(CultureInfo.InvariantCulture))); - } - - var id = IdGenerator.CreateDigitsId().ToString(CultureInfo.InvariantCulture); - var existWithId = this.GetById(id); - while (existWithId != null) - { - id = IdGenerator.CreateDigitsId().ToString(CultureInfo.InvariantCulture); - existWithId = this.GetById(id); - } - - model.TerritoryId = id; - - PropertyHelper.MakePropertiesEmptyIfNull(model); - - var territoryEntity = this.dataContext.Territories.Add(model); - this.dataContext.SaveChanges(); - - return territoryEntity.Entity; - } - - public TerritoryDb? Update(TerritoryDb model) - { - if (this.dataContext.Regions.FirstOrDefault(r => r.RegionId == model.RegionId) == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, StringTemplates.InvalidEntityMessage, nameof(model.Region), model.RegionId?.ToString(CultureInfo.InvariantCulture))); - } - - var territoryEntity = this.dataContext.Territories.FirstOrDefault(p => p.TerritoryId == model.TerritoryId); - if (territoryEntity != null) - { - territoryEntity.TerritoryDescription = model.TerritoryDescription != null ? model.TerritoryDescription : territoryEntity.TerritoryDescription; - territoryEntity.RegionId = model.RegionId != null ? model.RegionId : territoryEntity.RegionId; - - this.dataContext.SaveChanges(); - } - - return territoryEntity; - } - - public TerritoryDb? Delete(string id) - { - var territoryEntity = this.GetById(id); - if (territoryEntity != null) - { - this.dataContext.Territories.Remove(territoryEntity); - this.dataContext.SaveChanges(); - } - - return territoryEntity; + var territories = this.dataContext.Territories.Where(t => t.RegionId == id).ToArray(); + return this.mapper.Map(territories); } } } From 37a728c7345a1955b43cf57e27118b77bd607b79 Mon Sep 17 00:00:00 2001 From: Dimitar Georgiev Dimitrov Date: Wed, 23 Oct 2024 17:48:29 +0300 Subject: [PATCH 3/5] resolve conflicts and styling --- NorthwindCRUD.Tests/BaseFixture.cs | 1 + .../EmployeeTerritoryServiceFixture.cs | 4 +- NorthwindCRUD.Tests/Helpers/DataHelper.cs | 2 - NorthwindCRUD.Tests/RegionServiceFixture.cs | 1 - NorthwindCRUD/Controllers/BaseController.cs | 47 ++++--- .../Controllers/CategoriesController.cs | 7 +- .../Controllers/CustomersController.cs | 1 - .../Controllers/EmployeesController.cs | 14 +-- NorthwindCRUD/Controllers/OrdersController.cs | 2 +- .../Controllers/RegionsController.cs | 3 - .../Controllers/ShippersController.cs | 1 + .../Controllers/SuppliersController.cs | 1 - .../Controllers/TerritoriesController.cs | 14 --- NorthwindCRUD/DataContext.cs | 3 - NorthwindCRUD/Helpers/DBSeeder.cs | 20 +-- NorthwindCRUD/Helpers/MappingProfiles.cs | 115 +++++++++--------- NorthwindCRUD/Helpers/PropertyHelper.cs | 6 +- .../20241022072605_TablesToOwnAddress.cs | 48 ++++---- NorthwindCRUD/Models/Contracts/IOrder.cs | 1 + NorthwindCRUD/Models/DbModels/AddressDb.cs | 1 - NorthwindCRUD/Models/Dtos/AddressDto.cs | 2 + NorthwindCRUD/Models/Dtos/OrderDto.cs | 1 + NorthwindCRUD/Program.cs | 1 - NorthwindCRUD/Services/BaseDbService.cs | 57 +++++---- NorthwindCRUD/Services/CustomerService.cs | 4 +- .../Services/EmployeeTerritoryService.cs | 2 +- NorthwindCRUD/Services/ProductService.cs | 1 - NorthwindCRUD/Services/RegionService.cs | 1 - NorthwindCRUD/Services/TerritoryService.cs | 1 - 29 files changed, 166 insertions(+), 196 deletions(-) diff --git a/NorthwindCRUD.Tests/BaseFixture.cs b/NorthwindCRUD.Tests/BaseFixture.cs index 084b9d3..b2dbe3b 100644 --- a/NorthwindCRUD.Tests/BaseFixture.cs +++ b/NorthwindCRUD.Tests/BaseFixture.cs @@ -3,6 +3,7 @@ using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; +using NorthwindCRUD.Helpers; using NorthwindCRUD.Services; namespace NorthwindCRUD.Tests diff --git a/NorthwindCRUD.Tests/EmployeeTerritoryServiceFixture.cs b/NorthwindCRUD.Tests/EmployeeTerritoryServiceFixture.cs index d3c6088..8a384c2 100644 --- a/NorthwindCRUD.Tests/EmployeeTerritoryServiceFixture.cs +++ b/NorthwindCRUD.Tests/EmployeeTerritoryServiceFixture.cs @@ -13,7 +13,7 @@ public async Task ShouldAddTerritoryToEmployee() DataHelper.CreateEmployeeTerritory(employeeId, territoryId); - var territories = DataHelper2.EmployeeTerritoryService.GetTeritoriesByEmployeeId(employeeId); + var territories = DataHelper2.EmployeeTerritoryService.GetTerritoriesByEmployeeId(employeeId); Assert.IsNotNull(territories); Assert.IsTrue(territories.Any(t => t.TerritoryId == territoryId)); } @@ -28,7 +28,7 @@ public async Task ShouldReturnTerritoriesForEmployee() DataHelper.CreateEmployeeTerritory(employeeId, territoryId1); DataHelper.CreateEmployeeTerritory(employeeId, territoryId2); - var territories = DataHelper2.EmployeeTerritoryService.GetTeritoriesByEmployeeId(employeeId); + var territories = DataHelper2.EmployeeTerritoryService.GetTerritoriesByEmployeeId(employeeId); Assert.IsNotNull(territories); Assert.AreEqual(2, territories.Length); diff --git a/NorthwindCRUD.Tests/Helpers/DataHelper.cs b/NorthwindCRUD.Tests/Helpers/DataHelper.cs index 583c68d..2a18bcd 100644 --- a/NorthwindCRUD.Tests/Helpers/DataHelper.cs +++ b/NorthwindCRUD.Tests/Helpers/DataHelper.cs @@ -112,7 +112,6 @@ internal OrderDetailDto GetOrderDetail() return mapper.Map(orderDetail); } - internal async Task CreateSupplier() { var supplier = GetSupplier(); @@ -145,7 +144,6 @@ internal async Task CreateCustomer() return createdCustomer; } - internal async Task CreateOrder(string? orderDate = null, string? country = null, ProductDto? product = null, int? quantity = null) { var order = GetOrder(); diff --git a/NorthwindCRUD.Tests/RegionServiceFixture.cs b/NorthwindCRUD.Tests/RegionServiceFixture.cs index 4daac2e..136a76d 100644 --- a/NorthwindCRUD.Tests/RegionServiceFixture.cs +++ b/NorthwindCRUD.Tests/RegionServiceFixture.cs @@ -16,7 +16,6 @@ public async Task ShouldCreateRegion() createdRegion = DataHelper2.RegionService.GetById(createdRegion.RegionId); Assert.IsNotNull(createdRegion); Assert.AreEqual(region.RegionDescription, createdRegion.RegionDescription); - } [TestMethod] diff --git a/NorthwindCRUD/Controllers/BaseController.cs b/NorthwindCRUD/Controllers/BaseController.cs index 0ee6b89..026ee8b 100644 --- a/NorthwindCRUD/Controllers/BaseController.cs +++ b/NorthwindCRUD/Controllers/BaseController.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; @@ -26,6 +27,14 @@ public ActionResult GetAll() return Ok(result); } + [HttpGet("GetAllAuthorized")] + [Authorize] + public ActionResult GetAllAuthorized() + { + var result = this.baseDbService.GetAll(); + return Ok(result); + } + /// /// Fetches all customers or a page of customers based on the provided parameters. /// @@ -35,7 +44,7 @@ public ActionResult GetAll() /// A PagedResultDto object containing the fetched T and the total record count. [HttpGet("GetWithSkip")] public ActionResult> GetWithSkip( - [FromQuery][Attributes.SwaggerSkipParameter][Range(1, int.MaxValue, ErrorMessage = "Skip must be greater than 0.")] int? skip, + [FromQuery][Attributes.SwaggerSkipParameter][Range(0, int.MaxValue, ErrorMessage = "Skip must be greater than 0.")] int? skip, [FromQuery][Attributes.SwaggerTopParameter] int? top, [FromQuery][Attributes.SwaggerOrderByParameter] string? orderBy) { @@ -62,7 +71,7 @@ public ActionResult> GetWithPage( } [HttpPost] - //[Authorize] + [Authorize] public async Task> Create(TDto model) { if (!ModelState.IsValid) @@ -74,21 +83,8 @@ public async Task> Create(TDto model) return Ok(result); } - //[HttpPut("{id}")] - ////[Authorize] - //public async Task> Update(TDto model, TId id) - //{ - // if (!ModelState.IsValid) - // { - // return BadRequest(ModelState); - // } - - // var result = await this.baseDbService.Upsert(model, id); - // return Ok(result); - //} - [HttpPut] - //[Authorize] + [Authorize] public async Task> Update(TDto model) { if (!ModelState.IsValid) @@ -114,17 +110,28 @@ public ActionResult GetById(TId id) } /// - /// Retrieves the total number of customers. + /// Retrieves the total number of entities. /// - /// Total count of customers as an integer. + /// Total count of entities as an integer. [HttpGet("GetCount")] - public ActionResult GetCustomersCount() + public ActionResult GetCount() + { + return this.baseDbService.GetCount(); + } + + /// + /// Retrieves the total number of entities. + /// + /// Total count of entities as an integer. + [HttpGet("GetCountAuthorized")] + [Authorize] + public ActionResult GetCountAuthorized() { return this.baseDbService.GetCount(); } [HttpDelete("{id}")] - //[Authorize] + [Authorize] public ActionResult Delete(TId id) { var product = this.baseDbService.Delete(id); diff --git a/NorthwindCRUD/Controllers/CategoriesController.cs b/NorthwindCRUD/Controllers/CategoriesController.cs index 907166d..94c660b 100644 --- a/NorthwindCRUD/Controllers/CategoriesController.cs +++ b/NorthwindCRUD/Controllers/CategoriesController.cs @@ -1,7 +1,5 @@ namespace NorthwindCRUD.Controllers { - using System.ComponentModel.DataAnnotations; - using AutoMapper; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; @@ -13,15 +11,12 @@ public class CategoriesController : BaseNorthwindAPIController logger; - public CategoriesController(CategoryService categoryService, ProductService productService, IMapper mapper, ILogger logger) + public CategoriesController(CategoryService categoryService, ProductService productService) : base(categoryService) { this.categoryService = categoryService; this.productService = productService; - this.mapper = mapper; } [HttpGet("{id}/Details")] diff --git a/NorthwindCRUD/Controllers/CustomersController.cs b/NorthwindCRUD/Controllers/CustomersController.cs index bc1c82b..39d2156 100644 --- a/NorthwindCRUD/Controllers/CustomersController.cs +++ b/NorthwindCRUD/Controllers/CustomersController.cs @@ -1,6 +1,5 @@ namespace NorthwindCRUD.Controllers { - using System.ComponentModel.DataAnnotations; using AutoMapper; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; diff --git a/NorthwindCRUD/Controllers/EmployeesController.cs b/NorthwindCRUD/Controllers/EmployeesController.cs index 484015f..6c7dd05 100644 --- a/NorthwindCRUD/Controllers/EmployeesController.cs +++ b/NorthwindCRUD/Controllers/EmployeesController.cs @@ -55,16 +55,16 @@ public ActionResult GetOrdersByEmployeeId(int id) return Ok(orders); } - [HttpGet("{id}/Teritories")] - public ActionResult GetTeritoriesByEmployeeId(int id) + [HttpGet("{id}/Territories")] + public ActionResult GetTerritoriesByEmployeeId(int id) { - var teritories = this.employeeTerritoryService.GetTeritoriesByEmployeeId(id); - if (teritories == null) + var territories = this.employeeTerritoryService.GetTeritoriesByEmployeeId(id); + if (territories == null) { return NotFound($"No territories for employee {id}"); } - return Ok(teritories); + return Ok(territories); } [HttpPost("Teritory")] @@ -75,8 +75,8 @@ public ActionResult AddTerritoryToEmployee(EmployeeTerrito { if (ModelState.IsValid) { - var employeeTerrirtory = this.employeeTerritoryService.AddTerritoryToEmployee(model); - return Ok(employeeTerrirtory); + var employeeTerritory = this.employeeTerritoryService.AddTerritoryToEmployee(model); + return Ok(employeeTerritory); } return BadRequest(ModelState); diff --git a/NorthwindCRUD/Controllers/OrdersController.cs b/NorthwindCRUD/Controllers/OrdersController.cs index d9db324..9551089 100644 --- a/NorthwindCRUD/Controllers/OrdersController.cs +++ b/NorthwindCRUD/Controllers/OrdersController.cs @@ -77,7 +77,7 @@ public ActionResult GetShipperByOrderId(int id) var order = this.orderService.GetById(id); if (order != null) { - var shipper = this.shipperService.GetById(order.ShipVia); + var shipper = this.shipperService.GetById(id); if (shipper != null) { diff --git a/NorthwindCRUD/Controllers/RegionsController.cs b/NorthwindCRUD/Controllers/RegionsController.cs index c529e09..601fc2f 100644 --- a/NorthwindCRUD/Controllers/RegionsController.cs +++ b/NorthwindCRUD/Controllers/RegionsController.cs @@ -1,7 +1,5 @@ namespace NorthwindCRUD.Controllers { - using AutoMapper; - using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; @@ -22,7 +20,6 @@ public RegionsController(RegionService regionService, TerritoryService territory [HttpGet("{id}/Territories")] public ActionResult GetTerritoryByRegionId(int id) { - var region = this.baseDbService.GetById(id); if (region != null) { diff --git a/NorthwindCRUD/Controllers/ShippersController.cs b/NorthwindCRUD/Controllers/ShippersController.cs index 0fdf38b..cf798e0 100644 --- a/NorthwindCRUD/Controllers/ShippersController.cs +++ b/NorthwindCRUD/Controllers/ShippersController.cs @@ -14,6 +14,7 @@ public class ShippersController : BaseNorthwindAPIController> CreateAsync(TerritoryDto model) - //{ - // if (!ModelState.IsValid) - // { - // return BadRequest(ModelState); - // } - - // var result = await this.baseDbService.Upsert(model, default); - // return Ok(result); - //} - [HttpGet("{id}/Employees")] public ActionResult GetEmployeesByTerritory(string id) { diff --git a/NorthwindCRUD/DataContext.cs b/NorthwindCRUD/DataContext.cs index 08fd210..039b8b3 100644 --- a/NorthwindCRUD/DataContext.cs +++ b/NorthwindCRUD/DataContext.cs @@ -10,8 +10,6 @@ public DataContext(DbContextOptions options) { } - //public DbSet Addresses { get; set; } - public DbSet Categories { get; set; } public DbSet Customers { get; set; } @@ -93,6 +91,5 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity() .HasKey(et => new { et.ProductId, et.OrderId }); } - } } diff --git a/NorthwindCRUD/Helpers/DBSeeder.cs b/NorthwindCRUD/Helpers/DBSeeder.cs index 2bbad90..ecd0407 100644 --- a/NorthwindCRUD/Helpers/DBSeeder.cs +++ b/NorthwindCRUD/Helpers/DBSeeder.cs @@ -119,15 +119,7 @@ private static void SeedOrders(DataContext dbContext) { foreach (var order in parsedOrders) { - if (order.ShipAddress != null) - { - //if (dbContext.Addresses.FirstOrDefault(a => a.Street == order.ShipAddress.Street) == null) - //{ - // dbContext.Addresses.Add(order.ShipAddress); - //} - - dbContext.Orders.Add(order); - } + dbContext.Orders.Add(order); } dbContext.SaveChanges(); @@ -159,11 +151,6 @@ private static void SeedEmployees(DataContext dbContext) { foreach (var employee in parsedEmployees) { - //if (dbContext.Addresses.FirstOrDefault(a => a.Street == employee.Address.Street) == null) - //{ - // dbContext.Addresses.Add(employee.Address); - //} - dbContext.Employees.Add(employee); } @@ -187,11 +174,6 @@ private static void SeedCustomers(DataContext dbContext) if (existingCustomer == null) { - //if (dbContext.Addresses.FirstOrDefault(a => a.Street == customer.Address.Street) == null) - //{ - // dbContext.Addresses.Add(customer.Address); - //} - dbContext.Customers.Add(customer); } } diff --git a/NorthwindCRUD/Helpers/MappingProfiles.cs b/NorthwindCRUD/Helpers/MappingProfiles.cs index f6fc12e..7906c33 100644 --- a/NorthwindCRUD/Helpers/MappingProfiles.cs +++ b/NorthwindCRUD/Helpers/MappingProfiles.cs @@ -2,62 +2,65 @@ using NorthwindCRUD.Models.DbModels; using NorthwindCRUD.Models.Dtos; -public class MappingProfiles : Profile +namespace NorthwindCRUD.Helpers { - public MappingProfiles() + public class MappingProfiles : Profile { - // Entity to Entity (Ignoring ID fields) - CreateMap() - .ForMember(dest => dest.CategoryId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - CreateMap() - .ForMember(dest => dest.CustomerId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - CreateMap() - .ForMember(dest => dest.SupplierId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - CreateMap() - .ForMember(dest => dest.EmployeeId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - CreateMap() - .ForMember(dest => dest.TerritoryId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - CreateMap() - .ForMember(dest => dest.RegionId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - CreateMap() - .ForMember(dest => dest.OrderId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - CreateMap() - .ForMember(dest => dest.ProductId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - CreateMap() - .ForMember(dest => dest.ShipperId, opt => opt.Ignore()) - .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); - - // DTO to DB and Reverse mappings - CreateMap().ReverseMap(); - CreateMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); + public MappingProfiles() + { + // Entity to Entity (Ignoring ID fields) + CreateMap() + .ForMember(dest => dest.CategoryId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.CustomerId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.SupplierId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.EmployeeId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.TerritoryId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.RegionId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.OrderId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.ProductId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + CreateMap() + .ForMember(dest => dest.ShipperId, opt => opt.Ignore()) + .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); + + // DTO to DB and Reverse mappings + CreateMap().ReverseMap(); + CreateMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + } } -} +} \ No newline at end of file diff --git a/NorthwindCRUD/Helpers/PropertyHelper.cs b/NorthwindCRUD/Helpers/PropertyHelper.cs index e3a0cac..4f9d895 100644 --- a/NorthwindCRUD/Helpers/PropertyHelper.cs +++ b/NorthwindCRUD/Helpers/PropertyHelper.cs @@ -1,7 +1,7 @@ -namespace NorthwindCRUD.Helpers -{ - using System.Reflection; +using System.Reflection; +namespace NorthwindCRUD.Helpers +{ public static class PropertyHelper { [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "Need generic type here")] diff --git a/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.cs b/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.cs index e05a809..cd413f6 100644 --- a/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.cs +++ b/NorthwindCRUD/Migrations/20241022072605_TablesToOwnAddress.cs @@ -275,14 +275,14 @@ protected override void Up(MigrationBuilder migrationBuilder) table: "Employees", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "Address_Country", table: "Employees", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "Address_Phone", @@ -295,21 +295,21 @@ protected override void Up(MigrationBuilder migrationBuilder) table: "Employees", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "Address_Region", table: "Employees", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "Address_Street", table: "Employees", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "ReportsTo", @@ -339,7 +339,7 @@ protected override void Up(MigrationBuilder migrationBuilder) table: "Customers", type: "TEXT", nullable: false, - defaultValue: "", + defaultValue: string.Empty, oldClrType: typeof(string), oldType: "nvarchar(max)", oldNullable: true); @@ -357,14 +357,14 @@ protected override void Up(MigrationBuilder migrationBuilder) table: "Customers", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "Address_Country", table: "Customers", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "Address_Phone", @@ -377,21 +377,21 @@ protected override void Up(MigrationBuilder migrationBuilder) table: "Customers", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "Address_Region", table: "Customers", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AddColumn( name: "Address_Street", table: "Customers", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AlterColumn( name: "Name", @@ -423,14 +423,14 @@ protected override void Up(MigrationBuilder migrationBuilder) table: "Categories", type: "TEXT", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.CreateTable( name: "Regions", columns: table => new { RegionId = table.Column(type: "INTEGER", nullable: false), - RegionDescription = table.Column(type: "TEXT", nullable: false) + RegionDescription = table.Column(type: "TEXT", nullable: false), }, constraints: table => { @@ -443,7 +443,7 @@ protected override void Up(MigrationBuilder migrationBuilder) { ShipperId = table.Column(type: "INTEGER", nullable: false), CompanyName = table.Column(type: "TEXT", nullable: false), - Phone = table.Column(type: "TEXT", nullable: false) + Phone = table.Column(type: "TEXT", nullable: false), }, constraints: table => { @@ -466,7 +466,7 @@ protected override void Up(MigrationBuilder migrationBuilder) Country = table.Column(type: "TEXT", nullable: true), Phone = table.Column(type: "TEXT", nullable: true), Fax = table.Column(type: "TEXT", nullable: true), - HomePage = table.Column(type: "TEXT", nullable: true) + HomePage = table.Column(type: "TEXT", nullable: true), }, constraints: table => { @@ -479,7 +479,7 @@ protected override void Up(MigrationBuilder migrationBuilder) { TerritoryId = table.Column(type: "TEXT", nullable: false), RegionId = table.Column(type: "INTEGER", nullable: true), - TerritoryDescription = table.Column(type: "TEXT", nullable: false) + TerritoryDescription = table.Column(type: "TEXT", nullable: false), }, constraints: table => { @@ -504,7 +504,7 @@ protected override void Up(MigrationBuilder migrationBuilder) UnitsInStock = table.Column(type: "INTEGER", nullable: true), UnitsOnOrder = table.Column(type: "INTEGER", nullable: true), ReorderLevel = table.Column(type: "INTEGER", nullable: true), - Discontinued = table.Column(type: "INTEGER", nullable: false) + Discontinued = table.Column(type: "INTEGER", nullable: false), }, constraints: table => { @@ -528,7 +528,7 @@ protected override void Up(MigrationBuilder migrationBuilder) columns: table => new { EmployeeId = table.Column(type: "INTEGER", nullable: false), - TerritoryId = table.Column(type: "TEXT", nullable: false) + TerritoryId = table.Column(type: "TEXT", nullable: false), }, constraints: table => { @@ -555,7 +555,7 @@ protected override void Up(MigrationBuilder migrationBuilder) ProductId = table.Column(type: "INTEGER", nullable: false), UnitPrice = table.Column(type: "REAL", nullable: false), Quantity = table.Column(type: "INTEGER", nullable: false), - Discount = table.Column(type: "REAL", nullable: false) + Discount = table.Column(type: "REAL", nullable: false), }, constraints: table => { @@ -861,7 +861,7 @@ protected override void Down(MigrationBuilder migrationBuilder) table: "Orders", type: "nvarchar(max)", nullable: false, - defaultValue: "", + defaultValue: string.Empty, oldClrType: typeof(string), oldType: "TEXT", oldNullable: true); @@ -879,7 +879,7 @@ protected override void Down(MigrationBuilder migrationBuilder) table: "Orders", type: "nvarchar(450)", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AlterColumn( name: "TitleOfCourtesy", @@ -958,7 +958,7 @@ protected override void Down(MigrationBuilder migrationBuilder) table: "Employees", type: "nvarchar(450)", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AlterColumn( name: "ContactTitle", @@ -997,7 +997,7 @@ protected override void Down(MigrationBuilder migrationBuilder) table: "Customers", type: "nvarchar(450)", nullable: false, - defaultValue: ""); + defaultValue: string.Empty); migrationBuilder.AlterColumn( name: "Name", @@ -1034,7 +1034,7 @@ protected override void Down(MigrationBuilder migrationBuilder) Phone = table.Column(type: "nvarchar(max)", nullable: false), PostalCode = table.Column(type: "nvarchar(max)", nullable: false), Region = table.Column(type: "nvarchar(max)", nullable: false), - Street = table.Column(type: "nvarchar(max)", nullable: false) + Street = table.Column(type: "nvarchar(max)", nullable: false), }, constraints: table => { diff --git a/NorthwindCRUD/Models/Contracts/IOrder.cs b/NorthwindCRUD/Models/Contracts/IOrder.cs index 9f12415..a598d64 100644 --- a/NorthwindCRUD/Models/Contracts/IOrder.cs +++ b/NorthwindCRUD/Models/Contracts/IOrder.cs @@ -1,4 +1,5 @@ using NorthwindCRUD.Models.Dtos; +using static NorthwindCRUD.Helpers.Enums; namespace NorthwindCRUD.Models.Contracts { diff --git a/NorthwindCRUD/Models/DbModels/AddressDb.cs b/NorthwindCRUD/Models/DbModels/AddressDb.cs index 0907a34..300fc38 100644 --- a/NorthwindCRUD/Models/DbModels/AddressDb.cs +++ b/NorthwindCRUD/Models/DbModels/AddressDb.cs @@ -4,7 +4,6 @@ namespace NorthwindCRUD.Models.DbModels { public class AddressDb : IBaseDb, IAddress { - public string Street { get; set; } public string City { get; set; } diff --git a/NorthwindCRUD/Models/Dtos/AddressDto.cs b/NorthwindCRUD/Models/Dtos/AddressDto.cs index 0247d83..b3122ed 100644 --- a/NorthwindCRUD/Models/Dtos/AddressDto.cs +++ b/NorthwindCRUD/Models/Dtos/AddressDto.cs @@ -1,6 +1,8 @@ using System.ComponentModel.DataAnnotations; using NorthwindCRUD.Models.Contracts; +namespace NorthwindCRUD.Models.Dtos +{ public class AddressDto : IBaseDto, IAddress { [StringLength(100, ErrorMessage = "Street cannot exceed 100 characters.")] diff --git a/NorthwindCRUD/Models/Dtos/OrderDto.cs b/NorthwindCRUD/Models/Dtos/OrderDto.cs index 4d908d5..0b13bb1 100644 --- a/NorthwindCRUD/Models/Dtos/OrderDto.cs +++ b/NorthwindCRUD/Models/Dtos/OrderDto.cs @@ -2,6 +2,7 @@ { using System.ComponentModel.DataAnnotations; using NorthwindCRUD.Models.Contracts; + using static NorthwindCRUD.Helpers.Enums; public class OrderDto : IBaseDto, IOrder { diff --git a/NorthwindCRUD/Program.cs b/NorthwindCRUD/Program.cs index 0d41e37..6feff57 100644 --- a/NorthwindCRUD/Program.cs +++ b/NorthwindCRUD/Program.cs @@ -5,7 +5,6 @@ using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using Newtonsoft.Json.Converters; diff --git a/NorthwindCRUD/Services/BaseDbService.cs b/NorthwindCRUD/Services/BaseDbService.cs index caa33b8..ff19fb4 100644 --- a/NorthwindCRUD/Services/BaseDbService.cs +++ b/NorthwindCRUD/Services/BaseDbService.cs @@ -62,30 +62,6 @@ public IQueryable GetAllAsQueryable() return mapper.Map(dbResult); } - protected TDb GetDbById(TId id) - { - TDb dtoInstance = new TDb(); - - IQueryable query = this.dataContext.Set(); - foreach (var include in dtoInstance.GetIncludes()) - { - query = query.Include(include); - } - - var keyProperty = typeof(TDb).GetProperties() - .FirstOrDefault(p => Attribute.IsDefined(p, typeof(KeyAttribute))); - - if (keyProperty == null) - { - throw new InvalidOperationException("No key property found on entity"); - } - - TDb? dbResult = query.FirstOrDefault(entity => - EF.Property(entity, keyProperty.Name).Equals(id)); - - return dbResult; - } - public PagedResultDto GetWithPageSkip(int? skip = null, int? top = null, int? pageIndex = null, int? size = null, string? orderBy = null) { var query = GetAllAsQueryable(); @@ -105,9 +81,14 @@ public async Task Update(TDto model) throw new InvalidOperationException("No key property found on entity"); } - var keyValue = (TId)keyProperty.GetValue(model); + var keyValue = keyProperty.GetValue(model); + + if (keyValue == null) + { + throw new InvalidOperationException("Key property value cannot be null"); + } - return await Update(model, keyValue); + return await Update(model, (TId)keyValue); } public async Task Update(TDto model, TId id) @@ -164,5 +145,29 @@ public CountResultDto GetCount() Count = this.dataContext.Set().Count(), }; } + + protected TDb? GetDbById(TId id) + { + TDb dtoInstance = new TDb(); + + IQueryable query = this.dataContext.Set(); + foreach (var include in dtoInstance.GetIncludes()) + { + query = query.Include(include); + } + + var keyProperty = typeof(TDb).GetProperties() + .FirstOrDefault(p => Attribute.IsDefined(p, typeof(KeyAttribute))); + + if (keyProperty == null || string.IsNullOrEmpty(keyProperty.Name)) + { + throw new InvalidOperationException("No key property found on entity"); + } + + TDb? dbResult = query.FirstOrDefault(entity => + EF.Property(entity, keyProperty.Name)!.Equals(id)); + + return dbResult; + } } } diff --git a/NorthwindCRUD/Services/CustomerService.cs b/NorthwindCRUD/Services/CustomerService.cs index 2683399..b30678d 100644 --- a/NorthwindCRUD/Services/CustomerService.cs +++ b/NorthwindCRUD/Services/CustomerService.cs @@ -7,6 +7,8 @@ namespace NorthwindCRUD.Services public class CustomerService : BaseDbService { public CustomerService(DataContext dataContext, IPagingService pagingService, IMapper mapper) - : base(dataContext, mapper, pagingService) { } + : base(dataContext, mapper, pagingService) + { + } } } diff --git a/NorthwindCRUD/Services/EmployeeTerritoryService.cs b/NorthwindCRUD/Services/EmployeeTerritoryService.cs index 774aaab..c6d9cc4 100644 --- a/NorthwindCRUD/Services/EmployeeTerritoryService.cs +++ b/NorthwindCRUD/Services/EmployeeTerritoryService.cs @@ -36,7 +36,7 @@ public EmployeeTerritoryService(DataContext dataContext, IMapper mapper) } [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1011:Closing square brackets should be spaced correctly", Justification = "Need to return nullable type")] - public TerritoryDto[]? GetTeritoriesByEmployeeId(int id) + public TerritoryDto[]? GetTerritoriesByEmployeeId(int id) { var employee = this.dataContext.Employees .Include(c => c.Address) diff --git a/NorthwindCRUD/Services/ProductService.cs b/NorthwindCRUD/Services/ProductService.cs index e3acf27..57fd119 100644 --- a/NorthwindCRUD/Services/ProductService.cs +++ b/NorthwindCRUD/Services/ProductService.cs @@ -6,7 +6,6 @@ namespace NorthwindCRUD.Services { public class ProductService : BaseDbService { - public ProductService(DataContext dataContext, IPagingService pagingService, IMapper mapper) : base(dataContext, mapper, pagingService) { diff --git a/NorthwindCRUD/Services/RegionService.cs b/NorthwindCRUD/Services/RegionService.cs index 0c974bf..122453f 100644 --- a/NorthwindCRUD/Services/RegionService.cs +++ b/NorthwindCRUD/Services/RegionService.cs @@ -6,7 +6,6 @@ namespace NorthwindCRUD.Services { public class RegionService : BaseDbService { - public RegionService(DataContext dataContext, IPagingService pagingService, IMapper mapper) : base(dataContext, mapper, pagingService) { diff --git a/NorthwindCRUD/Services/TerritoryService.cs b/NorthwindCRUD/Services/TerritoryService.cs index 01e6059..d1dfc1f 100644 --- a/NorthwindCRUD/Services/TerritoryService.cs +++ b/NorthwindCRUD/Services/TerritoryService.cs @@ -6,7 +6,6 @@ namespace NorthwindCRUD.Services { public class TerritoryService : BaseDbService { - public TerritoryService(DataContext dataContext, IPagingService pagingService, IMapper mapper) : base(dataContext, mapper, pagingService) { From 390f6f2622cced7d9744eddfd8e65693de046f36 Mon Sep 17 00:00:00 2001 From: Dimitar Georgiev Dimitrov Date: Wed, 23 Oct 2024 17:57:30 +0300 Subject: [PATCH 4/5] typo --- NorthwindCRUD/Controllers/EmployeesController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NorthwindCRUD/Controllers/EmployeesController.cs b/NorthwindCRUD/Controllers/EmployeesController.cs index 6c7dd05..1d38f4c 100644 --- a/NorthwindCRUD/Controllers/EmployeesController.cs +++ b/NorthwindCRUD/Controllers/EmployeesController.cs @@ -58,7 +58,7 @@ public ActionResult GetOrdersByEmployeeId(int id) [HttpGet("{id}/Territories")] public ActionResult GetTerritoriesByEmployeeId(int id) { - var territories = this.employeeTerritoryService.GetTeritoriesByEmployeeId(id); + var territories = this.employeeTerritoryService.GetTerritoriesByEmployeeId(id); if (territories == null) { return NotFound($"No territories for employee {id}"); From b9443385840140ab126ea6a4f448a05794a162d8 Mon Sep 17 00:00:00 2001 From: Dimitar Georgiev Dimitrov Date: Wed, 23 Oct 2024 18:15:23 +0300 Subject: [PATCH 5/5] fix warnings --- NorthwindCRUD.Tests/SalesServiceFixture.cs | 2 ++ NorthwindCRUD/Controllers/BaseController.cs | 2 +- NorthwindCRUD/Controllers/EmployeesController.cs | 4 ++-- NorthwindCRUD/Controllers/RegionsController.cs | 4 +++- NorthwindCRUD/Controllers/TerritoriesController.cs | 4 +++- NorthwindCRUD/Models/DbModels/OrderDb.cs | 5 +++++ NorthwindCRUD/Services/BaseDbService.cs | 6 +++--- NorthwindCRUD/Services/CategoryService.cs | 6 +++++- NorthwindCRUD/Services/EmployeeService.cs | 4 +--- NorthwindCRUD/Services/OrderService.cs | 5 +++++ NorthwindCRUD/Services/ProductService.cs | 12 ++++++------ NorthwindCRUD/Services/TerritoryService.cs | 4 ++-- 12 files changed, 38 insertions(+), 20 deletions(-) diff --git a/NorthwindCRUD.Tests/SalesServiceFixture.cs b/NorthwindCRUD.Tests/SalesServiceFixture.cs index 31d9836..ae24bc7 100644 --- a/NorthwindCRUD.Tests/SalesServiceFixture.cs +++ b/NorthwindCRUD.Tests/SalesServiceFixture.cs @@ -60,6 +60,8 @@ public async Task ShouldRetrieveSalesDataByProductCategoryAndYear() Assert.IsNotNull(product.CategoryId); var category = DataHelper2.CategoryService.GetById((int)product.CategoryId); + + Assert.IsNotNull(category); SalesDto[] salesData = DataHelper2.SalesService.GetSalesDataByCategoryAndYear(category.Name, 2023); Assert.IsNotNull(salesData); diff --git a/NorthwindCRUD/Controllers/BaseController.cs b/NorthwindCRUD/Controllers/BaseController.cs index 026ee8b..3156dfa 100644 --- a/NorthwindCRUD/Controllers/BaseController.cs +++ b/NorthwindCRUD/Controllers/BaseController.cs @@ -13,7 +13,7 @@ public class BaseNorthwindAPIController : ControllerBase where TDto : class, IBaseDto where TDb : class, IBaseDb, new() { - protected readonly BaseDbService baseDbService; + private readonly BaseDbService baseDbService; public BaseNorthwindAPIController(BaseDbService baseDbService) { diff --git a/NorthwindCRUD/Controllers/EmployeesController.cs b/NorthwindCRUD/Controllers/EmployeesController.cs index 1d38f4c..9f5c03b 100644 --- a/NorthwindCRUD/Controllers/EmployeesController.cs +++ b/NorthwindCRUD/Controllers/EmployeesController.cs @@ -27,11 +27,11 @@ public EmployeesController(EmployeeService employeeService, EmployeeTerritorySer [HttpGet("{id}/Superior")] public ActionResult GetSuperiorById(int id) { - var employee = this.baseDbService.GetById(id); + var employee = this.employeeService.GetById(id); if (employee != null) { - var superior = this.baseDbService.GetById(employee.ReportsTo); + var superior = this.employeeService.GetById(employee.ReportsTo); if (superior != null) { diff --git a/NorthwindCRUD/Controllers/RegionsController.cs b/NorthwindCRUD/Controllers/RegionsController.cs index 601fc2f..82d2d34 100644 --- a/NorthwindCRUD/Controllers/RegionsController.cs +++ b/NorthwindCRUD/Controllers/RegionsController.cs @@ -9,18 +9,20 @@ [Route("[controller]")] public class RegionsController : BaseNorthwindAPIController { + private readonly RegionService regionService; private readonly TerritoryService territoryService; public RegionsController(RegionService regionService, TerritoryService territoryService, OrderService ordersService) : base(regionService) { + this.regionService = regionService; this.territoryService = territoryService; } [HttpGet("{id}/Territories")] public ActionResult GetTerritoryByRegionId(int id) { - var region = this.baseDbService.GetById(id); + var region = this.regionService.GetById(id); if (region != null) { var territories = this.territoryService.GetTerritoriesByRegionId(id); diff --git a/NorthwindCRUD/Controllers/TerritoriesController.cs b/NorthwindCRUD/Controllers/TerritoriesController.cs index 0dc18f7..7c5ccff 100644 --- a/NorthwindCRUD/Controllers/TerritoriesController.cs +++ b/NorthwindCRUD/Controllers/TerritoriesController.cs @@ -9,12 +9,14 @@ [Route("[controller]")] public class TerritoriesController : BaseNorthwindAPIController { + private readonly TerritoryService territoryService; private readonly RegionService regionService; private readonly EmployeeTerritoryService employeeTerritoryService; public TerritoriesController(TerritoryService territoryService, RegionService regionService, EmployeeTerritoryService employeeTerritoryService) : base(territoryService) { + this.territoryService = territoryService; this.regionService = regionService; this.employeeTerritoryService = employeeTerritoryService; } @@ -34,7 +36,7 @@ public ActionResult GetEmployeesByTerritory(string id) [HttpGet("{id}/Region")] public ActionResult GetRegionByTerritory(string id) { - var territory = this.baseDbService.GetById(id); + var territory = this.territoryService.GetById(id); if (territory != null) { var region = this.regionService.GetById(territory.RegionId ?? default); diff --git a/NorthwindCRUD/Models/DbModels/OrderDb.cs b/NorthwindCRUD/Models/DbModels/OrderDb.cs index f61c35e..f02932a 100644 --- a/NorthwindCRUD/Models/DbModels/OrderDb.cs +++ b/NorthwindCRUD/Models/DbModels/OrderDb.cs @@ -40,5 +40,10 @@ public class OrderDb : IBaseDb public bool Completed { get; set; } public AddressDb? ShipAddress { get; set; } + + public string[] GetIncludes() + { + return new string[] { "Employee", "Customer", "Shipper" }; + } } } diff --git a/NorthwindCRUD/Services/BaseDbService.cs b/NorthwindCRUD/Services/BaseDbService.cs index ff19fb4..ee3d082 100644 --- a/NorthwindCRUD/Services/BaseDbService.cs +++ b/NorthwindCRUD/Services/BaseDbService.cs @@ -11,8 +11,8 @@ public abstract class BaseDbService where TDto : class, IBaseDto where TDb : class, IBaseDb, new() { - protected readonly DataContext dataContext; - protected readonly IMapper mapper; + private readonly DataContext dataContext; + private readonly IMapper mapper; private readonly IPagingService pagingService; public BaseDbService(DataContext dataContext, IMapper mapper, IPagingService pagingService) @@ -165,7 +165,7 @@ public CountResultDto GetCount() } TDb? dbResult = query.FirstOrDefault(entity => - EF.Property(entity, keyProperty.Name)!.Equals(id)); + EF.Property(entity, keyProperty.Name) !.Equals(id)); return dbResult; } diff --git a/NorthwindCRUD/Services/CategoryService.cs b/NorthwindCRUD/Services/CategoryService.cs index af35a3f..aa2924f 100644 --- a/NorthwindCRUD/Services/CategoryService.cs +++ b/NorthwindCRUD/Services/CategoryService.cs @@ -6,15 +6,19 @@ public class CategoryService : BaseDbService { + private readonly IMapper mapper; + public CategoryService(DataContext dataContext, IPagingService pagingService, IMapper mapper) : base(dataContext, mapper, pagingService) { + this.mapper = mapper; } public CategoryDetailsDto GetDetailsById(int id) { var category = this.GetDbById(id); - return this.mapper.Map(category); + + return mapper.Map(category); } } } diff --git a/NorthwindCRUD/Services/EmployeeService.cs b/NorthwindCRUD/Services/EmployeeService.cs index cd134fb..367d022 100644 --- a/NorthwindCRUD/Services/EmployeeService.cs +++ b/NorthwindCRUD/Services/EmployeeService.cs @@ -13,9 +13,7 @@ public EmployeeService(DataContext dataContext, IPagingService pagingService, IM public EmployeeDto[] GetEmployeesByReportsTo(int id) { - return mapper.Map(this.dataContext.Employees - .Where(c => c.ReportsTo == id) - .ToArray()); + return this.GetAll().Where(c => c.ReportsTo == id).ToArray(); } } } diff --git a/NorthwindCRUD/Services/OrderService.cs b/NorthwindCRUD/Services/OrderService.cs index cf343e9..2349ad4 100644 --- a/NorthwindCRUD/Services/OrderService.cs +++ b/NorthwindCRUD/Services/OrderService.cs @@ -8,9 +8,14 @@ namespace NorthwindCRUD.Services { public class OrderService : BaseDbService { + private readonly IMapper mapper; + private readonly DataContext dataContext; + public OrderService(DataContext dataContext, IPagingService pagingService, IMapper mapper) : base(dataContext, mapper, pagingService) { + this.mapper = mapper; + this.dataContext = dataContext; } public OrderDto[] GetNOrders(int numberOfOrdersToRetrieve) diff --git a/NorthwindCRUD/Services/ProductService.cs b/NorthwindCRUD/Services/ProductService.cs index 57fd119..9198f4a 100644 --- a/NorthwindCRUD/Services/ProductService.cs +++ b/NorthwindCRUD/Services/ProductService.cs @@ -13,20 +13,20 @@ public ProductService(DataContext dataContext, IPagingService pagingService, IMa public ProductDto[] GetAllByCategoryId(int id) { - var products = this.dataContext.Products.Where(p => p.CategoryId == id).ToArray(); - return mapper.Map(products); + var products = this.GetAll().Where(p => p.CategoryId == id).ToArray(); + return products; } public ProductDto[] GetAllBySupplierId(int id) { - var products = this.dataContext.Products.Where(p => p.SupplierId == id).ToArray(); - return mapper.Map(products); + var products = this.GetAll().Where(p => p.SupplierId == id).ToArray(); + return products; } public ProductDto[] GetProductsByIds(int[] productIds) { - var products = this.dataContext.Products.Where(p => productIds.Contains(p.ProductId)).ToArray(); - return mapper.Map(products); + var products = this.GetAll().Where(p => productIds.Contains(p.ProductId)).ToArray(); + return products; } } } diff --git a/NorthwindCRUD/Services/TerritoryService.cs b/NorthwindCRUD/Services/TerritoryService.cs index d1dfc1f..b7d25b6 100644 --- a/NorthwindCRUD/Services/TerritoryService.cs +++ b/NorthwindCRUD/Services/TerritoryService.cs @@ -13,8 +13,8 @@ public TerritoryService(DataContext dataContext, IPagingService pagingService, I public TerritoryDto[] GetTerritoriesByRegionId(int id) { - var territories = this.dataContext.Territories.Where(t => t.RegionId == id).ToArray(); - return this.mapper.Map(territories); + var territories = this.GetAll().Where(t => t.RegionId == id).ToArray(); + return territories; } } }