Редактирование сущности-справочника

This commit is contained in:
Дмитрий Шурыгин 2024-12-23 16:07:01 +04:00
parent d307350c07
commit b0ca5df306
12 changed files with 169 additions and 27 deletions

View File

@ -5,7 +5,7 @@ public class Expenditure
public int Id { get; private set; }
public int ClothId { get; private set; }
public double Value { get; private set; }
public static Expenditure CreateOperation(int id, int clothId, double value)
public static Expenditure CreateElement(int id, int clothId, double value)
{
return new Expenditure
{

View File

@ -16,4 +16,14 @@ public class Model
Expenditures = expenditures
};
}
public static Model CreateEntity(TempExpenditure tempExpenditure, IEnumerable<Expenditure> expenditures)
{
return new Model
{
Id = tempExpenditure.Id,
ModelType = tempExpenditure.ModelType,
Expenditures = expenditures
};
}
}

View File

@ -0,0 +1,11 @@
using ProjectAtelier.Entities.Enums;
namespace ProjectAtelier.Entities;
public class TempExpenditure
{
public int Id { get; private set; }
public ModelType ModelType { get; private set; }
public int ClothId { get; private set; }
public double Value { get; private set; }
}

View File

@ -45,46 +45,42 @@
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.Margin = new Padding(3, 2, 3, 2);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 51;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(583, 338);
dataGridViewData.Size = new Size(666, 451);
dataGridViewData.TabIndex = 5;
//
// panel1
//
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(583, 0);
panel1.Margin = new Padding(3, 2, 3, 2);
panel1.Location = new Point(666, 0);
panel1.Name = "panel1";
panel1.Size = new Size(117, 338);
panel1.Size = new Size(134, 451);
panel1.TabIndex = 4;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.icons8_добавить_96;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(18, 14);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Location = new Point(21, 19);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(82, 69);
buttonAdd.Size = new Size(94, 92);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// FormEntrances
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(700, 338);
ClientSize = new Size(800, 451);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
Margin = new Padding(3, 2, 3, 2);
Name = "FormEntrances";
StartPosition = FormStartPosition.CenterParent;
Text = "История пополнений";

View File

@ -1,4 +1,5 @@
using ProjectAtelier.Repositories;
using ProjectAtelier.Repositories.Implementations;
using Unity;
namespace ProjectAtelier.Forms

View File

@ -1,12 +1,42 @@
using ProjectAtelier.Entities;
using ProjectAtelier.Entities.Enums;
using ProjectAtelier.Repositories;
using ProjectAtelier.Repositories.Implementations;
using System.Windows.Forms;
namespace ProjectAtelier.Forms
{
public partial class FormModel : Form
{
private readonly IModelRepository _modelRepository;
private int? _modelId;
public int Id
{
set
{
try
{
var model = _modelRepository.ReadModelById(value);
if (model == null)
{
throw new InvalidDataException(nameof(model));
}
comboBoxModelType.SelectedItem = model.ModelType;
foreach (var elem in model.Expenditures)
{
var row = dataGridViewCloths.Rows[dataGridViewCloths.Rows.Add()];
row.Cells["ColumnClothType"].Value = elem.ClothId;
row.Cells["ColumnValue"].Value = elem.Value;
}
_modelId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormModel(IOrderRepository orderRepository, IClothRepository clothRepository, IModelRepository modelRepository)
{
InitializeComponent();
@ -26,7 +56,14 @@ namespace ProjectAtelier.Forms
{
throw new Exception("Имеются незаполненные поля");
}
_modelRepository.CreateModel(Model.CreateEntity(0, (Entities.Enums.ModelType)(int)comboBoxModelType.SelectedValue!, CreateListExpenditureFromDataGrid()));
if (_modelId.HasValue)
{
_modelRepository.UpdateModel(CreateModel(_modelId.Value));
}
else
{
_modelRepository.CreateModel(Model.CreateEntity(0, (Entities.Enums.ModelType)(int)comboBoxModelType.SelectedValue!, CreateListExpenditureFromDataGrid()));
}
Close();
}
catch (Exception ex)
@ -35,9 +72,9 @@ namespace ProjectAtelier.Forms
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Model CreateModel(int id) => Model.CreateEntity(id, (Entities.Enums.ModelType)(int)comboBoxModelType.SelectedValue!, CreateListExpenditureFromDataGrid());
private List<Expenditure>
CreateListExpenditureFromDataGrid()
private List<Expenditure> CreateListExpenditureFromDataGrid()
{
var list = new List<Expenditure>();
foreach (DataGridViewRow row in dataGridViewCloths.Rows)
@ -46,9 +83,13 @@ namespace ProjectAtelier.Forms
{
continue;
}
list.Add(Expenditure.CreateOperation(0, Convert.ToInt32(row.Cells["ColumnClothType"].Value), Convert.ToInt32(row.Cells["ColumnValue"].Value)));
list.Add(Expenditure.CreateElement(0,
Convert.ToInt32(row.Cells["ColumnClothType"].Value),
Convert.ToInt32(row.Cells["ColumnValue"].Value)));
}
return list;
}
}
}

View File

@ -31,6 +31,7 @@
buttonDel = new Button();
buttonAdd = new Button();
panel1 = new Panel();
buttonUpd = new Button();
dataGridViewData = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
@ -40,7 +41,7 @@
//
buttonDel.BackgroundImage = Properties.Resources.icons8_удалить_100;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(18, 87);
buttonDel.Location = new Point(18, 160);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(82, 69);
@ -62,6 +63,7 @@
//
// panel1
//
panel1.Controls.Add(buttonUpd);
panel1.Controls.Add(buttonDel);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
@ -71,6 +73,18 @@
panel1.Size = new Size(117, 450);
panel1.TabIndex = 8;
//
// buttonUpd
//
buttonUpd.BackgroundImage = Properties.Resources.icons8_редактировать_96;
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpd.Location = new Point(18, 87);
buttonUpd.Margin = new Padding(3, 2, 3, 2);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(82, 69);
buttonUpd.TabIndex = 10;
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
@ -113,5 +127,6 @@
private Button buttonAdd;
private Panel panel1;
private DataGridView dataGridViewData;
private Button buttonUpd;
}
}

View File

@ -36,6 +36,24 @@ namespace ProjectAtelier.Forms
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormModel>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Microsoft ResX Schema
Version 2.0
@ -48,7 +48,7 @@
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter

View File

@ -19,6 +19,7 @@
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>

View File

@ -7,5 +7,6 @@ public interface IModelRepository
IEnumerable<Model> ReadModels();
Model ReadModelById(int id);
void CreateModel(Model model);
void UpdateModel(Model model);
void DeleteModel(int id);
}

View File

@ -3,10 +3,11 @@ using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectAtelier.Entities;
using System.Transactions;
namespace ProjectAtelier.Repositories.Implementations;
internal class ModelRepository : IModelRepository
public class ModelRepository : IModelRepository
{
private readonly IConnectionString _connectionString;
@ -50,6 +51,43 @@ VALUES (@modelId,@ClothId, @Value)";
throw;
}
}
public void UpdateModel(Model model)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(model));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryUpdate = @"
UPDATE Models
SET
ModelType=@ModelType
WHERE Id=@Id;
DELETE FROM Expenditures
WHERE ModelId=@Id";
connection.Execute(queryUpdate, model);
var querySubInsert = @"
INSERT INTO Expenditures (ModelId, ClothId, Value)
VALUES (@Id, @ClothId, @Value)";
foreach (var elem in model.Expenditures)
{
connection.Execute(querySubInsert, new
{
model.Id,
elem.ClothId,
elem.Value
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteModel(int id)
{
_logger.LogInformation("Удаление объекта");
@ -76,15 +114,20 @@ WHERE Id=@id";
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Models
WHERE Id=@id";
var model = connection.QueryFirst<Model>(querySelect, new
SELECT p.*, pc.ClothId, pc.Value FROM Models p
INNER JOIN Expenditures pc ON pc.ModelId = p.Id
WHERE p.Id=@id";
var model = connection.Query<TempExpenditure>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(model));
return model;
return model.GroupBy(x => x.Id, y => y,
(key, value) => Model.CreateEntity(value.First(),
value.Select(z => Expenditure.
CreateElement(0, z.ClothId, z.Value)))).ToList().First();
;
}
catch (Exception ex)
{
@ -98,11 +141,16 @@ WHERE Id=@id";
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Models";
var models = connection.Query<Model>(querySelect);
var querySelect = @"
SELECT p.*, pc.ClothId, pc.Value FROM Models p
INNER JOIN Expenditures pc ON pc.ModelId = p.Id";
var models = connection.Query<TempExpenditure>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(models));
return models;
return models.GroupBy(x => x.Id, y => y,
(key, value) => Model.CreateEntity(value.First(),
value.Select(z => Expenditure.
CreateElement(0, z.ClothId, z.Value)))).ToList();
}
catch (Exception ex)
{