diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Component.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Component.cs index 078d406..f5f2ee2 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Component.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Component.cs @@ -6,7 +6,7 @@ public class Component public string Name { get; private set; } = string.Empty; public double Price { get; private set; } public double Weight { get; private set; } - + public static Component CreateEntity(int id, string name, double price, double weight) { return new Component diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Order.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Order.cs index 14e25d8..042158a 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Order.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Order.cs @@ -1,4 +1,6 @@ -namespace ProjectConfectioneryFactory.Entities; +using System.ComponentModel; + +namespace ProjectConfectioneryFactory.Entities; public class Order { @@ -6,17 +8,30 @@ public class Order public int ClientId { get; private set; } public bool Completed { get; private set; } public DateTime Date { get; private set; } + public string Products => OrderProducts != null ? + string.Join(", ", OrderProducts.Select(x => $"{x.ProductName} {x.Count}")) : + string.Empty; + + [Browsable(false)] public IEnumerable OrderProducts { get; private set; } = []; - public static Order CreateOperation(int id, int clientid, bool completed, IEnumerable orderProducts) + public static Order CreateOperation(int id, int clientid, bool completed, DateTime date, IEnumerable orderProducts) { return new Order { Id = id, ClientId = clientid, Completed = completed, - Date = DateTime.Now, + Date = date, OrderProducts = orderProducts }; } + + public void SetOrderProducts(IEnumerable orderProducts) + { + if (orderProducts != null && orderProducts.Any()) + { + OrderProducts = orderProducts; + } + } } diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/OrderProduct.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/OrderProduct.cs index 9fd3cbe..8eff622 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/OrderProduct.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/OrderProduct.cs @@ -4,6 +4,7 @@ public class OrderProduct { public int OrderId { get; private set; } public int ProductId { get; private set; } + public string ProductName { get; private set; } = string.Empty; public int Count { get; private set; } public static OrderProduct CreateEntity(int orderid, int productid, int count) diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Product.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Product.cs index a94af95..171be15 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Product.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Product.cs @@ -1,4 +1,5 @@ using ProjectConfectioneryFactory.Entities.Enums; +using System.ComponentModel; namespace ProjectConfectioneryFactory.Entities; @@ -8,6 +9,11 @@ public class Product public ConfectioneryType ConfectioneryType { get; private set; } public string Name { get; private set; } = string.Empty; public double Price { get; private set; } + public string Components => ProductComponents != null ? + string.Join(", ", ProductComponents.Select(x => $"{x.ComponentName} {x.Weight}")) : + string.Empty; + + [Browsable(false)] public IEnumerable ProductComponents { get; private set; } = []; public static Product CreateEntity(int id, ConfectioneryType сonfectioneryType, string name, double price, IEnumerable productComponents) @@ -21,4 +27,12 @@ public class Product ProductComponents = productComponents }; } + + public void SetProductComponents(IEnumerable productComponents) + { + if (productComponents != null && productComponents.Any()) + { + ProductComponents = productComponents; + } + } } diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/ProductComponent.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/ProductComponent.cs index a98179e..0690459 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/ProductComponent.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/ProductComponent.cs @@ -4,6 +4,7 @@ public class ProductComponent { public int ProductId { get; private set; } public int ComponentId { get; private set; } + public string ComponentName { get; private set; } = string.Empty; public double Weight { get; private set; } public static ProductComponent CreateEntity(int productid, int componentid, double weight) diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Supply.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Supply.cs index a1a102c..5695275 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Supply.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Entities/Supply.cs @@ -9,7 +9,7 @@ public class Supply public bool Completed { get; private set; } public DateTime Date { get; private set; } - public static Supply CreateOperation(int id, int supplierid, int componentid, double weight, bool completed) + public static Supply CreateOperation(int id, int supplierid, int componentid, double weight, bool completed, DateTime date) { return new Supply { @@ -18,7 +18,7 @@ public class Supply ComponentId = componentid, Weight = weight, Completed = completed, - Date = DateTime.Now + Date = date }; } } diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/FormConfectioneryFactory.Designer.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/FormConfectioneryFactory.Designer.cs index 0d97521..99dbf5b 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/FormConfectioneryFactory.Designer.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/FormConfectioneryFactory.Designer.cs @@ -52,7 +52,7 @@ // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ClientsToolStripMenuItem, ProductsToolStripMenuItem, ComponentsToolStripMenuItem, SuppliersToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ClientsToolStripMenuItem, ComponentsToolStripMenuItem, ProductsToolStripMenuItem, SuppliersToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Text = "Справочники"; @@ -95,14 +95,14 @@ // OrdersToolStripMenuItem // OrdersToolStripMenuItem.Name = "OrdersToolStripMenuItem"; - OrdersToolStripMenuItem.Size = new Size(180, 22); + OrdersToolStripMenuItem.Size = new Size(126, 22); OrdersToolStripMenuItem.Text = "Заказы"; OrdersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; // // SupplysToolStripMenuItem // SupplysToolStripMenuItem.Name = "SupplysToolStripMenuItem"; - SupplysToolStripMenuItem.Size = new Size(180, 22); + SupplysToolStripMenuItem.Size = new Size(126, 22); SupplysToolStripMenuItem.Text = "Поставки"; SupplysToolStripMenuItem.Click += SupplysToolStripMenuItem_Click; // diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormClient.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormClient.cs index 685a38f..63e794e 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormClient.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormClient.cs @@ -1,6 +1,5 @@ using ProjectConfectioneryFactory.Entities; using ProjectConfectioneryFactory.Repositories; -using System.Text.RegularExpressions; namespace ProjectConfectioneryFactory.Forms { diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormComponent.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormComponent.cs index 6b38436..119fe1a 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormComponent.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormComponent.cs @@ -6,9 +6,9 @@ namespace ProjectConfectioneryFactory.Forms public partial class FormComponent : Form { private readonly IComponentRepository _componentRepository; - + private int? _componentId; - + public int Id { set @@ -34,7 +34,7 @@ namespace ProjectConfectioneryFactory.Forms InitializeComponent(); _componentRepository = componentRepository ?? throw new ArgumentNullException(nameof(componentRepository)); } - + private void ButtonSave_Click(object sender, EventArgs e) { try @@ -58,9 +58,9 @@ namespace ProjectConfectioneryFactory.Forms MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - + private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - + private Component CreateComponent(int id) => Component.CreateEntity( id, textBoxComponentName.Text, diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormOrder.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormOrder.cs index 138b5d0..39f732b 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormOrder.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormOrder.cs @@ -1,6 +1,5 @@ using ProjectConfectioneryFactory.Entities; using ProjectConfectioneryFactory.Repositories; -using ProjectConfectioneryFactory.Repositories.Implementations; namespace ProjectConfectioneryFactory.Forms { @@ -17,14 +16,26 @@ namespace ProjectConfectioneryFactory.Forms try { var order = _orderRepository.ReadOrderById(value); + if (order == null) { throw new InvalidDataException(nameof(order)); } + checkBoxCompleted.Checked = order.Completed; + dateTimePickerOrderDate.Value = order.Date; _orderId = value; + + foreach (OrderProduct elem in order.OrderProducts) + { + dataGridViewProducts.Rows.Add(elem.ProductId, elem.Count.ToString()); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; } - catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } @@ -61,15 +72,14 @@ namespace ProjectConfectioneryFactory.Forms } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка при сохранении", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - private ListCreateListOrderProductFromDataGrid() + private List CreateListOrderProductFromDataGrid(int id) { var list = new List(); foreach (DataGridViewRow row in dataGridViewProducts.Rows) @@ -79,16 +89,19 @@ namespace ProjectConfectioneryFactory.Forms { continue; } - list.Add(OrderProduct.CreateEntity(0, + list.Add(OrderProduct.CreateEntity( + id, Convert.ToInt32(row.Cells["ColumnProductName"].Value), Convert.ToInt32(row.Cells["ColumnProductCount"].Value))); } return list; } - private Order CreateOrder(int id) => Order.CreateOperation(0, + private Order CreateOrder(int id) => Order.CreateOperation( + id, (int)comboBoxClient.SelectedValue!, checkBoxCompleted.Checked, - CreateListOrderProductFromDataGrid()); + dateTimePickerOrderDate.Value, + CreateListOrderProductFromDataGrid(id)); } } diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormProduct.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormProduct.cs index 524d63a..c987a5b 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormProduct.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormProduct.cs @@ -17,10 +17,12 @@ namespace ProjectConfectioneryFactory.Forms try { var product = _productRepository.ReadProductById(value); + if (product == null) { throw new InvalidDataException(nameof(product)); } + foreach (ConfectioneryType elem in Enum.GetValues(typeof(ConfectioneryType))) { if ((elem & product.ConfectioneryType) != 0) @@ -31,6 +33,11 @@ namespace ProjectConfectioneryFactory.Forms textBoxProductName.Text = product.Name; numericUpDownPrice.Value = (decimal)product.Price; _productId = value; + + foreach (ProductComponent elem in product.ProductComponents) + { + dataGridViewComponents.Rows.Add(elem.ComponentId, elem.Weight.ToString()); + } } catch (Exception ex) { @@ -81,7 +88,7 @@ namespace ProjectConfectioneryFactory.Forms private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - private List CreateListProductComponentFromDataGrid() + private List CreateListProductComponentFromDataGrid(int id) { var list = new List(); foreach (DataGridViewRow row in dataGridViewComponents.Rows) @@ -91,7 +98,8 @@ namespace ProjectConfectioneryFactory.Forms { continue; } - list.Add(ProductComponent.CreateEntity(0, + list.Add(ProductComponent.CreateEntity( + id, Convert.ToInt32(row.Cells["ColumnComponent"].Value), Convert.ToDouble(row.Cells["ColumnWeight"].Value))); } @@ -110,7 +118,7 @@ namespace ProjectConfectioneryFactory.Forms confectioneryType, textBoxProductName.Text, (double)numericUpDownPrice.Value, - CreateListProductComponentFromDataGrid()); + CreateListProductComponentFromDataGrid(id)); } } } diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormSupply.Designer.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormSupply.Designer.cs index 97d6b41..d1f5ecd 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormSupply.Designer.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormSupply.Designer.cs @@ -28,7 +28,7 @@ /// private void InitializeComponent() { - dateTimePicker1 = new DateTimePicker(); + dateTimePickerSupplyDate = new DateTimePicker(); label2 = new Label(); buttonCancel = new Button(); buttonSave = new Button(); @@ -43,13 +43,13 @@ ((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit(); SuspendLayout(); // - // dateTimePicker1 + // dateTimePickerSupplyDate // - dateTimePicker1.Enabled = false; - dateTimePicker1.Location = new Point(108, 183); - dateTimePicker1.Name = "dateTimePicker1"; - dateTimePicker1.Size = new Size(200, 23); - dateTimePicker1.TabIndex = 32; + dateTimePickerSupplyDate.Enabled = false; + dateTimePickerSupplyDate.Location = new Point(108, 183); + dateTimePickerSupplyDate.Name = "dateTimePickerSupplyDate"; + dateTimePickerSupplyDate.Size = new Size(200, 23); + dateTimePickerSupplyDate.TabIndex = 32; // // label2 // @@ -164,7 +164,7 @@ Controls.Add(label5); Controls.Add(comboBoxComponent); Controls.Add(label3); - Controls.Add(dateTimePicker1); + Controls.Add(dateTimePickerSupplyDate); Controls.Add(label2); Controls.Add(buttonCancel); Controls.Add(buttonSave); @@ -182,7 +182,7 @@ #endregion - private DateTimePicker dateTimePicker1; + private DateTimePicker dateTimePickerSupplyDate; private Label label2; private Button buttonCancel; private Button buttonSave; diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormSupply.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormSupply.cs index bf12187..e7eb42f 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormSupply.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Forms/FormSupply.cs @@ -22,6 +22,7 @@ namespace ProjectConfectioneryFactory.Forms } numericUpDownWeight.Value = (decimal)supply.Weight; checkBoxCompleted.Checked = supply.Completed; + dateTimePickerSupplyDate.Value = supply.Date; _supplyId = value; } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } @@ -73,6 +74,7 @@ namespace ProjectConfectioneryFactory.Forms (int)comboBoxSupplier.SelectedValue!, (int)comboBoxComponent.SelectedValue!, Convert.ToDouble(numericUpDownWeight.Value), - checkBoxCompleted.Checked); + checkBoxCompleted.Checked, + dateTimePickerSupplyDate.Value); } } diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Program.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Program.cs index 8f38e2f..3aa9ef0 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Program.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Program.cs @@ -1,10 +1,10 @@ -using Unity.Lifetime; -using Unity; -using ProjectConfectioneryFactory.Repositories; -using ProjectConfectioneryFactory.Repositories.Implementations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; +using ProjectConfectioneryFactory.Repositories; +using ProjectConfectioneryFactory.Repositories.Implementations; using Serilog; +using Unity; +using Unity.Lifetime; using Unity.Microsoft.Logging; namespace ProjectConfectioneryFactory diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/ClientRepository.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/ClientRepository.cs index d58e01d..2ba1a3b 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/ClientRepository.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/ClientRepository.cs @@ -1,8 +1,8 @@ using Dapper; using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using ProjectConfectioneryFactory.Entities; using Npgsql; +using ProjectConfectioneryFactory.Entities; namespace ProjectConfectioneryFactory.Repositories.Implementations; diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/OrderRepository.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/OrderRepository.cs index 2574270..416b489 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/OrderRepository.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/OrderRepository.cs @@ -66,18 +66,19 @@ public class OrderRepository : IOrderRepository Completed=@Completed, Date=@Date WHERE Id=@Id"; - var orderId = connection.QueryFirst(queryUpdate, order, transaction); + connection.Execute(queryUpdate, order, transaction); - var querySubUpdate = @" - UPDATE OrderProducts - SET - OrderId=@OrderId, - ProductId=@ProductId, - Count=@Count - WHERE Id=@Id"; + var querySubDelete = @" + DELETE FROM OrderProducts + WHERE OrderId=@Id"; + connection.Execute(querySubDelete, order, transaction); + + var querySubInsert = @" + INSERT INTO OrderProducts (OrderId, ProductId, Count) + VALUES (@OrderId, @ProductId, @Count)"; foreach (var elem in order.OrderProducts) { - connection.Execute(querySubUpdate, new { orderId, elem.ProductId, elem.Count }, transaction); + connection.Execute(querySubInsert, elem, transaction); } transaction.Commit(); @@ -115,12 +116,43 @@ public class OrderRepository : IOrderRepository { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @" - SELECT * - FROM Orders - WHERE Id=@id"; - var order = connection.QueryFirst(querySelect, new { id }); - _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(order)); - return order; + SELECT + o.*, + op.OrderId, + op.ProductId, + p.Name AS ProductName, + op.Count + FROM Orders o + LEFT JOIN OrderProducts op ON op.OrderId = o.id + LEFT JOIN Products p ON p.id = op.productid + WHERE o.Id = @Id"; + + var productsDict = new Dictionary>(); + + var orders = connection.Query(querySelect, + (order, orderProduct) => + { + if (!productsDict.TryGetValue(order.Id, out var pc)) + { + pc = []; + productsDict.Add(order.Id, pc); + } + pc.Add(orderProduct); + return order; + }, + new { id }, + splitOn: "ProductId"); + + orders = productsDict.Select(x => + { + var pc = orders.First(y => y.Id == x.Key); + pc.SetOrderProducts(x.Value); + return pc; + }).ToArray(); + + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(orders)); + + return orders.First(); } catch (Exception ex) { @@ -135,9 +167,40 @@ public class OrderRepository : IOrderRepository try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = "SELECT * FROM Orders"; - var orders = connection.Query(querySelect); - _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders)); + var querySelect = @" + SELECT + o.*, + op.OrderId, + op.ProductId, + p.Name AS ProductName, + op.Count + FROM Orders o + LEFT JOIN OrderProducts op ON op.OrderId = o.id + LEFT JOIN Products p ON p.id = op.productid"; + + var productsDict = new Dictionary>(); + + var orders = connection.Query(querySelect, + (order, orderProduct) => + { + if (!productsDict.TryGetValue(order.Id, out var pc)) + { + pc = []; + productsDict.Add(order.Id, pc); + } + pc.Add(orderProduct); + return order; + }, splitOn: "ProductId"); + + orders = productsDict.Select(x => + { + var pc = orders.First(y => y.Id == x.Key); + pc.SetOrderProducts(x.Value); + return pc; + }).ToArray(); + + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(orders)); + return orders; } catch (Exception ex) diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/ProductRepository.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/ProductRepository.cs index 1fef377..84edce8 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/ProductRepository.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/ProductRepository.cs @@ -1,10 +1,8 @@ using Dapper; using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using ProjectConfectioneryFactory.Entities; -using ProjectConfectioneryFactory.Entities.Enums; using Npgsql; -using System.Transactions; +using ProjectConfectioneryFactory.Entities; namespace ProjectConfectioneryFactory.Repositories.Implementations; @@ -68,18 +66,19 @@ public class ProductRepository : IProductRepository Name=@Name, Price=@Price WHERE Id=@Id"; - var productId = connection.QueryFirst(queryUpdate, product, transaction); - - var querySubUpdate = @" - UPDATE ProductComponents - SET - ProductId=@ProductId, - ComponentId=@ComponentId, - Weight=@Weight - WHERE Id=@Id"; + connection.Execute(queryUpdate, product, transaction); + + var querySubDelete = @" + DELETE FROM ProductComponents + WHERE ProductId=@Id"; + connection.Execute(querySubDelete, product, transaction); + + var querySubInsert = @" + INSERT INTO ProductComponents (ProductId, ComponentId, Weight) + VALUES (@ProductId, @ComponentId, @Weight)"; foreach (var elem in product.ProductComponents) { - connection.Execute(querySubUpdate, new { productId, elem.ComponentId, elem.Weight }, transaction); + connection.Execute(querySubInsert, elem, transaction); } transaction.Commit(); } @@ -115,12 +114,43 @@ public class ProductRepository : IProductRepository { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @" - SELECT * - FROM Products - WHERE Id=@Id"; - var product = connection.QueryFirst(querySelect, new { id }); - _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product)); - return product; + SELECT + p.*, + pc.ProductId, + pc.ComponentId, + c.Name AS ComponentName, + pc.Weight + FROM Products p + LEFT JOIN ProductComponents pc ON pc.productid = p.id + LEFT JOIN Components c ON c.id = pc.componentid + WHERE p.Id = @Id"; + + var componentsDict = new Dictionary>(); + + var products = connection.Query(querySelect, + (product, productComponent) => + { + if (!componentsDict.TryGetValue(product.Id, out var pc)) + { + pc = []; + componentsDict.Add(product.Id, pc); + } + pc.Add(productComponent); + return product; + }, + new { id }, + splitOn: "ProductId"); + + products = componentsDict.Select(x => + { + var pc = products.First(y => y.Id == x.Key); + pc.SetProductComponents(x.Value); + return pc; + }).ToArray(); + + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(products)); + + return products.First(); } catch (Exception ex) { @@ -135,9 +165,40 @@ public class ProductRepository : IProductRepository try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @"SELECT * FROM Products"; - var products = connection.Query(querySelect); + var querySelect = @" + SELECT + p.*, + pc.ProductId, + pc.ComponentId, + c.Name AS ComponentName, + pc.Weight + FROM Products p + LEFT JOIN ProductComponents pc ON pc.productid = p.id + LEFT JOIN Components c ON c.id = pc.componentid"; + + var componentsDict = new Dictionary>(); + + var products = connection.Query(querySelect, + (product, productComponent) => + { + if (!componentsDict.TryGetValue(product.Id, out var pc)) + { + pc = []; + componentsDict.Add(product.Id, pc); + } + pc.Add(productComponent); + return product; + }, splitOn: "ProductId"); + + products = componentsDict.Select(x => + { + var pc = products.First(y => y.Id == x.Key); + pc.SetProductComponents(x.Value); + return pc; + }).ToArray(); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(products)); + return products; } catch (Exception ex) diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/SupplierRepository.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/SupplierRepository.cs index 4ee121c..c09bb75 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/SupplierRepository.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/SupplierRepository.cs @@ -1,8 +1,8 @@ using Dapper; using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using ProjectConfectioneryFactory.Entities; using Npgsql; +using ProjectConfectioneryFactory.Entities; namespace ProjectConfectioneryFactory.Repositories.Implementations; diff --git a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/SupplyRepository.cs b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/SupplyRepository.cs index 617c3e4..38dbb02 100644 --- a/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/SupplyRepository.cs +++ b/ProjectConfectioneryFactory/ProjectConfectioneryFactory/Repositories/Implementations/SupplyRepository.cs @@ -1,8 +1,8 @@ using Dapper; using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using ProjectConfectioneryFactory.Entities; using Npgsql; +using ProjectConfectioneryFactory.Entities; namespace ProjectConfectioneryFactory.Repositories.Implementations;