Лаб2 сделана

This commit is contained in:
Pyro 2024-12-25 00:24:24 +04:00
parent b0e19ce372
commit 015f034590
19 changed files with 259 additions and 82 deletions

View File

@ -1,4 +1,6 @@
namespace ProjectConfectioneryFactory.Entities; using System.ComponentModel;
namespace ProjectConfectioneryFactory.Entities;
public class Order public class Order
{ {
@ -6,17 +8,30 @@ public class Order
public int ClientId { get; private set; } public int ClientId { get; private set; }
public bool Completed { get; private set; } public bool Completed { get; private set; }
public DateTime Date { 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<OrderProduct> OrderProducts { get; private set; } = []; public IEnumerable<OrderProduct> OrderProducts { get; private set; } = [];
public static Order CreateOperation(int id, int clientid, bool completed, IEnumerable<OrderProduct> orderProducts) public static Order CreateOperation(int id, int clientid, bool completed, DateTime date, IEnumerable<OrderProduct> orderProducts)
{ {
return new Order return new Order
{ {
Id = id, Id = id,
ClientId = clientid, ClientId = clientid,
Completed = completed, Completed = completed,
Date = DateTime.Now, Date = date,
OrderProducts = orderProducts OrderProducts = orderProducts
}; };
} }
public void SetOrderProducts(IEnumerable<OrderProduct> orderProducts)
{
if (orderProducts != null && orderProducts.Any())
{
OrderProducts = orderProducts;
}
}
} }

View File

@ -4,6 +4,7 @@ public class OrderProduct
{ {
public int OrderId { get; private set; } public int OrderId { get; private set; }
public int ProductId { get; private set; } public int ProductId { get; private set; }
public string ProductName { get; private set; } = string.Empty;
public int Count { get; private set; } public int Count { get; private set; }
public static OrderProduct CreateEntity(int orderid, int productid, int count) public static OrderProduct CreateEntity(int orderid, int productid, int count)

View File

@ -1,4 +1,5 @@
using ProjectConfectioneryFactory.Entities.Enums; using ProjectConfectioneryFactory.Entities.Enums;
using System.ComponentModel;
namespace ProjectConfectioneryFactory.Entities; namespace ProjectConfectioneryFactory.Entities;
@ -8,6 +9,11 @@ public class Product
public ConfectioneryType ConfectioneryType { get; private set; } public ConfectioneryType ConfectioneryType { get; private set; }
public string Name { get; private set; } = string.Empty; public string Name { get; private set; } = string.Empty;
public double Price { get; private set; } 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<ProductComponent> ProductComponents { get; private set; } = []; public IEnumerable<ProductComponent> ProductComponents { get; private set; } = [];
public static Product CreateEntity(int id, ConfectioneryType сonfectioneryType, string name, double price, IEnumerable<ProductComponent> productComponents) public static Product CreateEntity(int id, ConfectioneryType сonfectioneryType, string name, double price, IEnumerable<ProductComponent> productComponents)
@ -21,4 +27,12 @@ public class Product
ProductComponents = productComponents ProductComponents = productComponents
}; };
} }
public void SetProductComponents(IEnumerable<ProductComponent> productComponents)
{
if (productComponents != null && productComponents.Any())
{
ProductComponents = productComponents;
}
}
} }

View File

@ -4,6 +4,7 @@ public class ProductComponent
{ {
public int ProductId { get; private set; } public int ProductId { get; private set; }
public int ComponentId { get; private set; } public int ComponentId { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Weight { get; private set; } public double Weight { get; private set; }
public static ProductComponent CreateEntity(int productid, int componentid, double weight) public static ProductComponent CreateEntity(int productid, int componentid, double weight)

View File

@ -9,7 +9,7 @@ public class Supply
public bool Completed { get; private set; } public bool Completed { get; private set; }
public DateTime Date { 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 return new Supply
{ {
@ -18,7 +18,7 @@ public class Supply
ComponentId = componentid, ComponentId = componentid,
Weight = weight, Weight = weight,
Completed = completed, Completed = completed,
Date = DateTime.Now Date = date
}; };
} }
} }

View File

@ -52,7 +52,7 @@
// //
// справочникиToolStripMenuItem // справочникиToolStripMenuItem
// //
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ClientsToolStripMenuItem, ProductsToolStripMenuItem, ComponentsToolStripMenuItem, SuppliersToolStripMenuItem }); справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ClientsToolStripMenuItem, ComponentsToolStripMenuItem, ProductsToolStripMenuItem, SuppliersToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники"; справочникиToolStripMenuItem.Text = "Справочники";
@ -95,14 +95,14 @@
// OrdersToolStripMenuItem // OrdersToolStripMenuItem
// //
OrdersToolStripMenuItem.Name = "OrdersToolStripMenuItem"; OrdersToolStripMenuItem.Name = "OrdersToolStripMenuItem";
OrdersToolStripMenuItem.Size = new Size(180, 22); OrdersToolStripMenuItem.Size = new Size(126, 22);
OrdersToolStripMenuItem.Text = "Заказы"; OrdersToolStripMenuItem.Text = "Заказы";
OrdersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; OrdersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
// //
// SupplysToolStripMenuItem // SupplysToolStripMenuItem
// //
SupplysToolStripMenuItem.Name = "SupplysToolStripMenuItem"; SupplysToolStripMenuItem.Name = "SupplysToolStripMenuItem";
SupplysToolStripMenuItem.Size = new Size(180, 22); SupplysToolStripMenuItem.Size = new Size(126, 22);
SupplysToolStripMenuItem.Text = "Поставки"; SupplysToolStripMenuItem.Text = "Поставки";
SupplysToolStripMenuItem.Click += SupplysToolStripMenuItem_Click; SupplysToolStripMenuItem.Click += SupplysToolStripMenuItem_Click;
// //

View File

@ -1,6 +1,5 @@
using ProjectConfectioneryFactory.Entities; using ProjectConfectioneryFactory.Entities;
using ProjectConfectioneryFactory.Repositories; using ProjectConfectioneryFactory.Repositories;
using System.Text.RegularExpressions;
namespace ProjectConfectioneryFactory.Forms namespace ProjectConfectioneryFactory.Forms
{ {

View File

@ -1,6 +1,5 @@
using ProjectConfectioneryFactory.Entities; using ProjectConfectioneryFactory.Entities;
using ProjectConfectioneryFactory.Repositories; using ProjectConfectioneryFactory.Repositories;
using ProjectConfectioneryFactory.Repositories.Implementations;
namespace ProjectConfectioneryFactory.Forms namespace ProjectConfectioneryFactory.Forms
{ {
@ -17,14 +16,26 @@ namespace ProjectConfectioneryFactory.Forms
try try
{ {
var order = _orderRepository.ReadOrderById(value); var order = _orderRepository.ReadOrderById(value);
if (order == null) if (order == null)
{ {
throw new InvalidDataException(nameof(order)); throw new InvalidDataException(nameof(order));
} }
checkBoxCompleted.Checked = order.Completed; checkBoxCompleted.Checked = order.Completed;
dateTimePickerOrderDate.Value = order.Date;
_orderId = value; _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) catch (Exception ex)
{ {
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
private void ButtonCancel_Click(object sender, EventArgs e) => Close(); private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<OrderProduct>CreateListOrderProductFromDataGrid() private List<OrderProduct> CreateListOrderProductFromDataGrid(int id)
{ {
var list = new List<OrderProduct>(); var list = new List<OrderProduct>();
foreach (DataGridViewRow row in dataGridViewProducts.Rows) foreach (DataGridViewRow row in dataGridViewProducts.Rows)
@ -79,16 +89,19 @@ namespace ProjectConfectioneryFactory.Forms
{ {
continue; continue;
} }
list.Add(OrderProduct.CreateEntity(0, list.Add(OrderProduct.CreateEntity(
id,
Convert.ToInt32(row.Cells["ColumnProductName"].Value), Convert.ToInt32(row.Cells["ColumnProductName"].Value),
Convert.ToInt32(row.Cells["ColumnProductCount"].Value))); Convert.ToInt32(row.Cells["ColumnProductCount"].Value)));
} }
return list; return list;
} }
private Order CreateOrder(int id) => Order.CreateOperation(0, private Order CreateOrder(int id) => Order.CreateOperation(
id,
(int)comboBoxClient.SelectedValue!, (int)comboBoxClient.SelectedValue!,
checkBoxCompleted.Checked, checkBoxCompleted.Checked,
CreateListOrderProductFromDataGrid()); dateTimePickerOrderDate.Value,
CreateListOrderProductFromDataGrid(id));
} }
} }

View File

@ -17,10 +17,12 @@ namespace ProjectConfectioneryFactory.Forms
try try
{ {
var product = _productRepository.ReadProductById(value); var product = _productRepository.ReadProductById(value);
if (product == null) if (product == null)
{ {
throw new InvalidDataException(nameof(product)); throw new InvalidDataException(nameof(product));
} }
foreach (ConfectioneryType elem in Enum.GetValues(typeof(ConfectioneryType))) foreach (ConfectioneryType elem in Enum.GetValues(typeof(ConfectioneryType)))
{ {
if ((elem & product.ConfectioneryType) != 0) if ((elem & product.ConfectioneryType) != 0)
@ -31,6 +33,11 @@ namespace ProjectConfectioneryFactory.Forms
textBoxProductName.Text = product.Name; textBoxProductName.Text = product.Name;
numericUpDownPrice.Value = (decimal)product.Price; numericUpDownPrice.Value = (decimal)product.Price;
_productId = value; _productId = value;
foreach (ProductComponent elem in product.ProductComponents)
{
dataGridViewComponents.Rows.Add(elem.ComponentId, elem.Weight.ToString());
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -81,7 +88,7 @@ namespace ProjectConfectioneryFactory.Forms
private void ButtonCancel_Click(object sender, EventArgs e) => Close(); private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<ProductComponent> CreateListProductComponentFromDataGrid() private List<ProductComponent> CreateListProductComponentFromDataGrid(int id)
{ {
var list = new List<ProductComponent>(); var list = new List<ProductComponent>();
foreach (DataGridViewRow row in dataGridViewComponents.Rows) foreach (DataGridViewRow row in dataGridViewComponents.Rows)
@ -91,7 +98,8 @@ namespace ProjectConfectioneryFactory.Forms
{ {
continue; continue;
} }
list.Add(ProductComponent.CreateEntity(0, list.Add(ProductComponent.CreateEntity(
id,
Convert.ToInt32(row.Cells["ColumnComponent"].Value), Convert.ToInt32(row.Cells["ColumnComponent"].Value),
Convert.ToDouble(row.Cells["ColumnWeight"].Value))); Convert.ToDouble(row.Cells["ColumnWeight"].Value)));
} }
@ -110,7 +118,7 @@ namespace ProjectConfectioneryFactory.Forms
confectioneryType, confectioneryType,
textBoxProductName.Text, textBoxProductName.Text,
(double)numericUpDownPrice.Value, (double)numericUpDownPrice.Value,
CreateListProductComponentFromDataGrid()); CreateListProductComponentFromDataGrid(id));
} }
} }
} }

View File

@ -28,7 +28,7 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
dateTimePicker1 = new DateTimePicker(); dateTimePickerSupplyDate = new DateTimePicker();
label2 = new Label(); label2 = new Label();
buttonCancel = new Button(); buttonCancel = new Button();
buttonSave = new Button(); buttonSave = new Button();
@ -43,13 +43,13 @@
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit(); ((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// dateTimePicker1 // dateTimePickerSupplyDate
// //
dateTimePicker1.Enabled = false; dateTimePickerSupplyDate.Enabled = false;
dateTimePicker1.Location = new Point(108, 183); dateTimePickerSupplyDate.Location = new Point(108, 183);
dateTimePicker1.Name = "dateTimePicker1"; dateTimePickerSupplyDate.Name = "dateTimePickerSupplyDate";
dateTimePicker1.Size = new Size(200, 23); dateTimePickerSupplyDate.Size = new Size(200, 23);
dateTimePicker1.TabIndex = 32; dateTimePickerSupplyDate.TabIndex = 32;
// //
// label2 // label2
// //
@ -164,7 +164,7 @@
Controls.Add(label5); Controls.Add(label5);
Controls.Add(comboBoxComponent); Controls.Add(comboBoxComponent);
Controls.Add(label3); Controls.Add(label3);
Controls.Add(dateTimePicker1); Controls.Add(dateTimePickerSupplyDate);
Controls.Add(label2); Controls.Add(label2);
Controls.Add(buttonCancel); Controls.Add(buttonCancel);
Controls.Add(buttonSave); Controls.Add(buttonSave);
@ -182,7 +182,7 @@
#endregion #endregion
private DateTimePicker dateTimePicker1; private DateTimePicker dateTimePickerSupplyDate;
private Label label2; private Label label2;
private Button buttonCancel; private Button buttonCancel;
private Button buttonSave; private Button buttonSave;

View File

@ -22,6 +22,7 @@ namespace ProjectConfectioneryFactory.Forms
} }
numericUpDownWeight.Value = (decimal)supply.Weight; numericUpDownWeight.Value = (decimal)supply.Weight;
checkBoxCompleted.Checked = supply.Completed; checkBoxCompleted.Checked = supply.Completed;
dateTimePickerSupplyDate.Value = supply.Date;
_supplyId = value; _supplyId = value;
} }
catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
@ -73,6 +74,7 @@ namespace ProjectConfectioneryFactory.Forms
(int)comboBoxSupplier.SelectedValue!, (int)comboBoxSupplier.SelectedValue!,
(int)comboBoxComponent.SelectedValue!, (int)comboBoxComponent.SelectedValue!,
Convert.ToDouble(numericUpDownWeight.Value), Convert.ToDouble(numericUpDownWeight.Value),
checkBoxCompleted.Checked); checkBoxCompleted.Checked,
dateTimePickerSupplyDate.Value);
} }
} }

View File

@ -1,10 +1,10 @@
using Unity.Lifetime;
using Unity;
using ProjectConfectioneryFactory.Repositories;
using ProjectConfectioneryFactory.Repositories.Implementations;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ProjectConfectioneryFactory.Repositories;
using ProjectConfectioneryFactory.Repositories.Implementations;
using Serilog; using Serilog;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging; using Unity.Microsoft.Logging;
namespace ProjectConfectioneryFactory namespace ProjectConfectioneryFactory

View File

@ -1,8 +1,8 @@
using Dapper; using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql; using Npgsql;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations; namespace ProjectConfectioneryFactory.Repositories.Implementations;

View File

@ -66,18 +66,19 @@ public class OrderRepository : IOrderRepository
Completed=@Completed, Completed=@Completed,
Date=@Date Date=@Date
WHERE Id=@Id"; WHERE Id=@Id";
var orderId = connection.QueryFirst<int>(queryUpdate, order, transaction); connection.Execute(queryUpdate, order, transaction);
var querySubUpdate = @" var querySubDelete = @"
UPDATE OrderProducts DELETE FROM OrderProducts
SET WHERE OrderId=@Id";
OrderId=@OrderId, connection.Execute(querySubDelete, order, transaction);
ProductId=@ProductId,
Count=@Count var querySubInsert = @"
WHERE Id=@Id"; INSERT INTO OrderProducts (OrderId, ProductId, Count)
VALUES (@OrderId, @ProductId, @Count)";
foreach (var elem in order.OrderProducts) foreach (var elem in order.OrderProducts)
{ {
connection.Execute(querySubUpdate, new { orderId, elem.ProductId, elem.Count }, transaction); connection.Execute(querySubInsert, elem, transaction);
} }
transaction.Commit(); transaction.Commit();
@ -115,12 +116,43 @@ public class OrderRepository : IOrderRepository
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" var querySelect = @"
SELECT * SELECT
FROM Orders o.*,
WHERE Id=@id"; op.OrderId,
var order = connection.QueryFirst<Order>(querySelect, new { id }); op.ProductId,
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(order)); p.Name AS ProductName,
return order; 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<int, List<OrderProduct>>();
var orders = connection.Query<Order, OrderProduct, Order>(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) catch (Exception ex)
{ {
@ -135,9 +167,40 @@ public class OrderRepository : IOrderRepository
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Orders"; var querySelect = @"
var orders = connection.Query<Order>(querySelect); SELECT
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders)); 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<int, List<OrderProduct>>();
var orders = connection.Query<Order, OrderProduct, Order>(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; return orders;
} }
catch (Exception ex) catch (Exception ex)

View File

@ -1,10 +1,8 @@
using Dapper; using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using ProjectConfectioneryFactory.Entities.Enums;
using Npgsql; using Npgsql;
using System.Transactions; using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations; namespace ProjectConfectioneryFactory.Repositories.Implementations;
@ -68,18 +66,19 @@ public class ProductRepository : IProductRepository
Name=@Name, Name=@Name,
Price=@Price Price=@Price
WHERE Id=@Id"; WHERE Id=@Id";
var productId = connection.QueryFirst<int>(queryUpdate, product, transaction); connection.Execute(queryUpdate, product, transaction);
var querySubUpdate = @" var querySubDelete = @"
UPDATE ProductComponents DELETE FROM ProductComponents
SET WHERE ProductId=@Id";
ProductId=@ProductId, connection.Execute(querySubDelete, product, transaction);
ComponentId=@ComponentId,
Weight=@Weight var querySubInsert = @"
WHERE Id=@Id"; INSERT INTO ProductComponents (ProductId, ComponentId, Weight)
VALUES (@ProductId, @ComponentId, @Weight)";
foreach (var elem in product.ProductComponents) foreach (var elem in product.ProductComponents)
{ {
connection.Execute(querySubUpdate, new { productId, elem.ComponentId, elem.Weight }, transaction); connection.Execute(querySubInsert, elem, transaction);
} }
transaction.Commit(); transaction.Commit();
} }
@ -115,12 +114,43 @@ public class ProductRepository : IProductRepository
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" var querySelect = @"
SELECT * SELECT
FROM Products p.*,
WHERE Id=@Id"; pc.ProductId,
var product = connection.QueryFirst<Product>(querySelect, new { id }); pc.ComponentId,
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product)); c.Name AS ComponentName,
return product; 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<int, List<ProductComponent>>();
var products = connection.Query<Product, ProductComponent, Product>(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) catch (Exception ex)
{ {
@ -135,9 +165,40 @@ public class ProductRepository : IProductRepository
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Products"; var querySelect = @"
var products = connection.Query<Product>(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<int, List<ProductComponent>>();
var products = connection.Query<Product, ProductComponent, Product>(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)); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(products));
return products; return products;
} }
catch (Exception ex) catch (Exception ex)

View File

@ -1,8 +1,8 @@
using Dapper; using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql; using Npgsql;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations; namespace ProjectConfectioneryFactory.Repositories.Implementations;

View File

@ -1,8 +1,8 @@
using Dapper; using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql; using Npgsql;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations; namespace ProjectConfectioneryFactory.Repositories.Implementations;