Compare commits

..

5 Commits

Author SHA1 Message Date
abazov73
69b21488e6 Add word table documemt creation 2023-11-30 01:45:08 +04:00
abazov73
295edcaaa9 Change fields to properties 2023-11-30 00:55:32 +04:00
abazov73
105c89cda0 Create PDF doc 2023-11-30 00:51:17 +04:00
abazov73
93ffc24a90 Add avatars and avatar document 2023-11-30 00:23:56 +04:00
abazov73
c3d19cda92 Finished CRUD part 2023-11-29 23:40:28 +04:00
22 changed files with 604 additions and 230 deletions

View File

@ -38,16 +38,16 @@ namespace AbazovViewComponents.Components
TreeNode? node = treeView.SelectedNode; TreeNode? node = treeView.SelectedNode;
var type = typeof(T); var type = typeof(T);
var fields = type.GetFields(); var properties = type.GetProperties();
var item = Activator.CreateInstance(type); var item = Activator.CreateInstance(type);
while (node != null) while (node != null)
{ {
var field = fields.FirstOrDefault(x => x.Name == node.Name); var property = properties.FirstOrDefault(x => x.Name == node.Name);
if (field != null) if (property != null)
{ {
field.SetValue(item, node.Text); property.SetValue(item, node.Text);
} }
node = node.Parent; node = node.Parent;
} }
@ -63,23 +63,23 @@ namespace AbazovViewComponents.Components
public void addItems<T>(List<T> items) public void addItems<T>(List<T> items)
{ {
var type = typeof(T); var type = typeof(T);
var fields = type.GetFields(); var properties = type.GetProperties();
foreach (T item in items) foreach (T item in items)
{ {
TreeNodeCollection nodes = treeView.Nodes; TreeNodeCollection nodes = treeView.Nodes;
for (int i = 0; i < hierarchy.Count; i++) for (int i = 0; i < hierarchy.Count; i++)
{ {
var field = fields.FirstOrDefault(x => x.Name.Equals(hierarchy[i].Item1)); var property = properties.FirstOrDefault(x => x.Name.Equals(hierarchy[i].Item1));
if (field is not null) if (property is not null)
{ {
var node = nodes.Find(field.Name, false).FirstOrDefault(x => x.Text == field.GetValue(item).ToString()); var node = nodes.Find(property.Name, false).FirstOrDefault(x => x.Text == property.GetValue(item).ToString());
if (node is not null && !hierarchy[i].Item2) if (node is not null && !hierarchy[i].Item2)
{ {
nodes = node.Nodes; nodes = node.Nodes;
} }
else else
{ {
TreeNode newNode = nodes.Add(field.Name, field.GetValue(item).ToString()); TreeNode newNode = nodes.Add(property.Name, property.GetValue(item).ToString());
nodes = newNode.Nodes; nodes = newNode.Nodes;
} }
} }

View File

@ -32,8 +32,8 @@ namespace AbazovViewComponents.LogicalComponents
{ {
Worksheet worksheet = (Worksheet)workbook.Worksheets.get_Item(1); Worksheet worksheet = (Worksheet)workbook.Worksheets.get_Item(1);
FieldInfo? seriesName = typeof(T).GetField(seriesNameField); PropertyInfo? seriesName = typeof(T).GetProperty(seriesNameField);
FieldInfo? value = typeof(T).GetField(valueField); PropertyInfo? value = typeof(T).GetProperty(valueField);
if (seriesName == null || value == null) throw new ArgumentException("Переданного поля не существует"); if (seriesName == null || value == null) throw new ArgumentException("Переданного поля не существует");
int columnCount = 2; int columnCount = 2;
foreach(var item in data) foreach(var item in data)

View File

@ -15,10 +15,12 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="NevaevaLibrary" Version="1.0.0" /> <PackageReference Include="NevaevaLibrary" Version="2.0.0" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="7.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AbazovViewComponents\AbazovViewComponents.csproj" />
<ProjectReference Include="..\AccountsBusinessLogic\AccountsBusinessLogic.csproj" /> <ProjectReference Include="..\AccountsBusinessLogic\AccountsBusinessLogic.csproj" />
<ProjectReference Include="..\AccountsDataBaseImplement\AccountsDataBaseImplement.csproj" /> <ProjectReference Include="..\AccountsDataBaseImplement\AccountsDataBaseImplement.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -28,19 +28,166 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.label1 = new System.Windows.Forms.Label();
this.textBoxLogin = new System.Windows.Forms.TextBox();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.mailControl = new NevaevaLibrary.MailControl();
this.abazovCheckedListBox = new AbazovViewComponents.Components.AbazovCheckedListBox();
this.label4 = new System.Windows.Forms.Label();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.buttonAvatar = new System.Windows.Forms.Button();
this.SuspendLayout(); this.SuspendLayout();
// //
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(52, 20);
this.label1.TabIndex = 0;
this.label1.Text = "Логин";
//
// textBoxLogin
//
this.textBoxLogin.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.textBoxLogin.Location = new System.Drawing.Point(12, 32);
this.textBoxLogin.Name = "textBoxLogin";
this.textBoxLogin.Size = new System.Drawing.Size(389, 27);
this.textBoxLogin.TabIndex = 1;
//
// textBoxPassword
//
this.textBoxPassword.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.textBoxPassword.Location = new System.Drawing.Point(12, 86);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.Size = new System.Drawing.Size(389, 27);
this.textBoxPassword.TabIndex = 3;
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 63);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(62, 20);
this.label2.TabIndex = 2;
this.label2.Text = "Пароль";
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 116);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(51, 20);
this.label3.TabIndex = 4;
this.label3.Text = "Почта";
//
// mailControl
//
this.mailControl.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.mailControl.Email = null;
this.mailControl.Location = new System.Drawing.Point(12, 139);
this.mailControl.Name = "mailControl";
this.mailControl.Size = new System.Drawing.Size(389, 42);
this.mailControl.TabIndex = 5;
this.mailControl.validateEmailRegex = null;
//
// abazovCheckedListBox
//
this.abazovCheckedListBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.abazovCheckedListBox.Location = new System.Drawing.Point(12, 207);
this.abazovCheckedListBox.Name = "abazovCheckedListBox";
this.abazovCheckedListBox.selectedItem = null;
this.abazovCheckedListBox.Size = new System.Drawing.Size(389, 130);
this.abazovCheckedListBox.TabIndex = 6;
//
// label4
//
this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(12, 184);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(78, 20);
this.label4.TabIndex = 7;
this.label4.Text = "Интересы";
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(12, 420);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 8;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(307, 420);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 9;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
//
// buttonAvatar
//
this.buttonAvatar.Location = new System.Drawing.Point(12, 343);
this.buttonAvatar.Name = "buttonAvatar";
this.buttonAvatar.Size = new System.Drawing.Size(389, 29);
this.buttonAvatar.TabIndex = 10;
this.buttonAvatar.Text = "Выбрать аватар";
this.buttonAvatar.UseVisualStyleBackColor = true;
this.buttonAvatar.Click += new System.EventHandler(this.buttonAvatar_Click);
//
// FormAccount // FormAccount
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450); this.ClientSize = new System.Drawing.Size(413, 461);
this.Controls.Add(this.buttonAvatar);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.label4);
this.Controls.Add(this.abazovCheckedListBox);
this.Controls.Add(this.mailControl);
this.Controls.Add(this.label3);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBoxLogin);
this.Controls.Add(this.label1);
this.Name = "FormAccount"; this.Name = "FormAccount";
this.Text = "Аккаунт"; this.Text = "Аккаунт";
this.Load += new System.EventHandler(this.FormAccount_Load);
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout();
} }
#endregion #endregion
private Label label1;
private TextBox textBoxLogin;
private TextBox textBoxPassword;
private Label label2;
private Label label3;
private NevaevaLibrary.MailControl mailControl;
private AbazovViewComponents.Components.AbazovCheckedListBox abazovCheckedListBox;
private Label label4;
private Button buttonSave;
private Button buttonCancel;
private OpenFileDialog openFileDialog;
private Button buttonAvatar;
} }
} }

View File

@ -1,4 +1,9 @@
using System; using AccountsContracts.BindingModels;
using AccountsContracts.BusinessLogicContracts;
using AccountsContracts.SearchModels;
using AccountsContracts.ViewModels;
using AccountsDataModels.Models;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -12,9 +17,114 @@ namespace AccountsApp
{ {
public partial class FormAccount : Form public partial class FormAccount : Form
{ {
public FormAccount() private int? _id;
private readonly IAccountLogic _logic;
private readonly IInterestLogic _interestLogic;
private List<InterestViewModel> _interests;
private string? avatar = null;
public int Id { set { _id = value; } }
public FormAccount(IAccountLogic logic, IInterestLogic interestLogic)
{ {
InitializeComponent(); InitializeComponent();
_logic = logic;
_interestLogic = interestLogic;
_interests = new List<InterestViewModel>();
}
private void FormAccount_Load(object sender, EventArgs e)
{
_interests = _interestLogic.ReadList(null);
abazovCheckedListBox.addItems(_interests.Select(x => x.Name).ToList());
mailControl.validateEmailRegex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
mailControl.setTooltipText("name@example.com");
if (_id.HasValue)
{
try
{
var view = _logic.ReadElement(new AccountSearchModel { Id = _id.Value });
if (view != null)
{
textBoxLogin.Text = view.Login;
textBoxPassword.Text = view.Password;
mailControl.Email = view.Email;
avatar = view.Avatar;
abazovCheckedListBox.selectedItem = view.InterestName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxLogin.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(mailControl.Email))
{
MessageBox.Show("Заполните почту или исправьте написание почты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (abazovCheckedListBox.selectedItem == null)
{
MessageBox.Show("Заполните интересы", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (avatar == null)
{
MessageBox.Show("Выберите аватар", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var model = new AccountBindingModel
{
Id = _id ?? 0,
Login = textBoxLogin.Text,
Password = textBoxPassword.Text,
Email = mailControl.Email,
InterestId = _interests.First(x => x.Name == abazovCheckedListBox.selectedItem).Id,
Avatar = avatar
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonAvatar_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() != DialogResult.Cancel)
{
avatar = openFileDialog.FileName;
}
} }
} }
} }

View File

@ -57,4 +57,7 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root> </root>

View File

@ -28,7 +28,7 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.controlDataTableAccounts = new ControlsLibraryNet60.Data.ControlDataTableTable(); this.components = new System.ComponentModel.Container();
this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.аккаунтыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.аккаунтыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.создатьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.создатьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
@ -39,19 +39,13 @@
this.документСТаблицейToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.документСТаблицейToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.документСДиаграммойToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.документСДиаграммойToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.интересыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.интересыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.controlDataTable = new ControlsLibraryNet60.Data.ControlDataTableTable();
this.excelImagesComponent = new AbazovViewComponents.LogicalComponents.ExcelImagesComponent(this.components);
this.wordTableComponentAccount = new NevaevaLibrary.LogicalComponents.WordTableComponent(this.components);
this.componentDocumentWithChartBarPdf = new ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarPdf(this.components);
this.menuStrip1.SuspendLayout(); this.menuStrip1.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
// //
// controlDataTableAccounts
//
this.controlDataTableAccounts.Dock = System.Windows.Forms.DockStyle.Fill;
this.controlDataTableAccounts.Location = new System.Drawing.Point(0, 28);
this.controlDataTableAccounts.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.controlDataTableAccounts.Name = "controlDataTableAccounts";
this.controlDataTableAccounts.SelectedRowIndex = -1;
this.controlDataTableAccounts.Size = new System.Drawing.Size(800, 422);
this.controlDataTableAccounts.TabIndex = 0;
//
// menuStrip1 // menuStrip1
// //
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
@ -89,6 +83,7 @@
this.редактироватьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.U))); this.редактироватьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.U)));
this.редактироватьToolStripMenuItem.Size = new System.Drawing.Size(246, 26); this.редактироватьToolStripMenuItem.Size = new System.Drawing.Size(246, 26);
this.редактироватьToolStripMenuItem.Text = "Редактировать"; this.редактироватьToolStripMenuItem.Text = "Редактировать";
this.редактироватьToolStripMenuItem.Click += new System.EventHandler(this.редактироватьToolStripMenuItem_Click);
// //
// удалитьToolStripMenuItem // удалитьToolStripMenuItem
// //
@ -96,6 +91,7 @@
this.удалитьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D))); this.удалитьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
this.удалитьToolStripMenuItem.Size = new System.Drawing.Size(246, 26); this.удалитьToolStripMenuItem.Size = new System.Drawing.Size(246, 26);
this.удалитьToolStripMenuItem.Text = "Удалить"; this.удалитьToolStripMenuItem.Text = "Удалить";
this.удалитьToolStripMenuItem.Click += new System.EventHandler(this.удалитьToolStripMenuItem_Click);
// //
// отчётыToolStripMenuItem // отчётыToolStripMenuItem
// //
@ -113,6 +109,7 @@
this.документToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.документToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.документToolStripMenuItem.Size = new System.Drawing.Size(313, 26); this.документToolStripMenuItem.Size = new System.Drawing.Size(313, 26);
this.документToolStripMenuItem.Text = "Документ"; this.документToolStripMenuItem.Text = "Документ";
this.документToolStripMenuItem.Click += new System.EventHandler(this.документToolStripMenuItem_Click);
// //
// документСТаблицейToolStripMenuItem // документСТаблицейToolStripMenuItem
// //
@ -120,6 +117,7 @@
this.документСТаблицейToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.T))); this.документСТаблицейToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.T)));
this.документСТаблицейToolStripMenuItem.Size = new System.Drawing.Size(313, 26); this.документСТаблицейToolStripMenuItem.Size = new System.Drawing.Size(313, 26);
this.документСТаблицейToolStripMenuItem.Text = "Документ с таблицей"; this.документСТаблицейToolStripMenuItem.Text = "Документ с таблицей";
this.документСТаблицейToolStripMenuItem.Click += new System.EventHandler(this.документСТаблицейToolStripMenuItem_Click);
// //
// документСДиаграммойToolStripMenuItem // документСДиаграммойToolStripMenuItem
// //
@ -127,6 +125,7 @@
this.документСДиаграммойToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C))); this.документСДиаграммойToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.документСДиаграммойToolStripMenuItem.Size = new System.Drawing.Size(313, 26); this.документСДиаграммойToolStripMenuItem.Size = new System.Drawing.Size(313, 26);
this.документСДиаграммойToolStripMenuItem.Text = "Документ с диаграммой"; this.документСДиаграммойToolStripMenuItem.Text = "Документ с диаграммой";
this.документСДиаграммойToolStripMenuItem.Click += new System.EventHandler(this.документСДиаграммойToolStripMenuItem_Click);
// //
// интересыToolStripMenuItem // интересыToolStripMenuItem
// //
@ -135,16 +134,27 @@
this.интересыToolStripMenuItem.Text = "Интересы"; this.интересыToolStripMenuItem.Text = "Интересы";
this.интересыToolStripMenuItem.Click += new System.EventHandler(this.интересыToolStripMenuItem_Click); this.интересыToolStripMenuItem.Click += new System.EventHandler(this.интересыToolStripMenuItem_Click);
// //
// controlDataTable
//
this.controlDataTable.Dock = System.Windows.Forms.DockStyle.Fill;
this.controlDataTable.Location = new System.Drawing.Point(0, 28);
this.controlDataTable.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.controlDataTable.Name = "controlDataTable";
this.controlDataTable.SelectedRowIndex = -1;
this.controlDataTable.Size = new System.Drawing.Size(800, 422);
this.controlDataTable.TabIndex = 2;
//
// FormMain // FormMain
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450); this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.controlDataTableAccounts); this.Controls.Add(this.controlDataTable);
this.Controls.Add(this.menuStrip1); this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1; this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMain"; this.Name = "FormMain";
this.Text = "Аккаунты"; this.Text = "Аккаунты";
this.Load += new System.EventHandler(this.FormMain_Load);
this.menuStrip1.ResumeLayout(false); this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout(); this.menuStrip1.PerformLayout();
this.ResumeLayout(false); this.ResumeLayout(false);
@ -153,8 +163,6 @@
} }
#endregion #endregion
private ControlsLibraryNet60.Data.ControlDataTableTable controlDataTableAccounts;
private MenuStrip menuStrip1; private MenuStrip menuStrip1;
private ToolStripMenuItem аккаунтыToolStripMenuItem; private ToolStripMenuItem аккаунтыToolStripMenuItem;
private ToolStripMenuItem создатьToolStripMenuItem; private ToolStripMenuItem создатьToolStripMenuItem;
@ -165,5 +173,9 @@
private ToolStripMenuItem документСТаблицейToolStripMenuItem; private ToolStripMenuItem документСТаблицейToolStripMenuItem;
private ToolStripMenuItem документСДиаграммойToolStripMenuItem; private ToolStripMenuItem документСДиаграммойToolStripMenuItem;
private ToolStripMenuItem интересыToolStripMenuItem; private ToolStripMenuItem интересыToolStripMenuItem;
private ControlsLibraryNet60.Data.ControlDataTableTable controlDataTable;
private AbazovViewComponents.LogicalComponents.ExcelImagesComponent excelImagesComponent;
private NevaevaLibrary.LogicalComponents.WordTableComponent wordTableComponentAccount;
private ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarPdf componentDocumentWithChartBarPdf;
} }
} }

View File

@ -1,4 +1,11 @@
using System; using AbazovViewComponents.LogicalComponents;
using AccountsContracts.BindingModels;
using AccountsContracts.BusinessLogicContracts;
using AccountsContracts.ViewModels;
using ComponentsLibraryNet60.Models;
using ControlsLibraryNet60.Core;
using ControlsLibraryNet60.Models;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -12,9 +19,19 @@ namespace AccountsApp
{ {
public partial class FormMain : Form public partial class FormMain : Form
{ {
public FormMain() private IAccountLogic _logic;
public FormMain(IAccountLogic logic)
{ {
InitializeComponent(); InitializeComponent();
_logic = logic;
controlDataTable.LoadColumns(new List<DataTableColumnConfig> {
new DataTableColumnConfig { ColumnHeader = "", PropertyName = "Id", Visible = false, Width = 10},
new DataTableColumnConfig { ColumnHeader = "Логин", PropertyName = "Login", Visible = true, Width = 200},
new DataTableColumnConfig { ColumnHeader = "Выбранный интерес", PropertyName = "InterestName", Visible = true, Width = 200},
new DataTableColumnConfig { ColumnHeader = "Email", PropertyName = "Email", Visible = true, Width = 200},
});
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
} }
private void создатьToolStripMenuItem_Click(object sender, EventArgs e) private void создатьToolStripMenuItem_Click(object sender, EventArgs e)
@ -24,7 +41,7 @@ namespace AccountsApp
{ {
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData();
} }
} }
} }
@ -37,5 +54,93 @@ namespace AccountsApp
form.ShowDialog(); form.ShowDialog();
} }
} }
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
controlDataTable.Clear();
var accounts = _logic.ReadList(null);
if (accounts != null)
{
controlDataTable.AddTable(accounts);
}
}
private void редактироватьToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormAccount));
if (service is FormAccount form)
{
form.Id = controlDataTable.GetSelectedObject<AccountViewModel>().Id;
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить запись?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
if (_logic.Delete(new AccountBindingModel { Id = controlDataTable.GetSelectedObject<AccountViewModel>().Id }))
{
LoadData();
}
}
}
private void документToolStripMenuItem_Click(object sender, EventArgs e)
{
List<string> avatars = new List<string>();
foreach (var account in _logic.ReadList(null))
{
avatars.Add(account.Avatar);
}
string path = AppDomain.CurrentDomain.BaseDirectory + "Аватары.xlsx";
if (excelImagesComponent.createWithImages(new ExcelImageInfo(path, "Аватары", avatars.ToArray()))) MessageBox.Show("Документ создан");
}
private void документСДиаграммойToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Интересы.pdf";
Dictionary<string, List<(int, double)>> data = new Dictionary<string, List<(int, double)>>();
data = _logic
.ReadList(null)
.GroupBy(x => x.InterestName)
.ToDictionary(x => x.Key, x => new List<(int, double)> { (0, x.Count())});
componentDocumentWithChartBarPdf.CreateDoc(new ComponentDocumentWithChartConfig
{
Header = "Интересы",
FilePath = path,
ChartTitle = "Интересы",
LegendLocation = ComponentsLibraryNet60.Models.Location.Bottom,
Data = data,
});
MessageBox.Show("Успех");
}
private void документСТаблицейToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Аккаунты.docx";
List<(int, int)> merges = new List<(int, int)> { (1, 2) };
List<int> widths = new List<int> { 100, 100, 100, 100 };
List<(string, string)> headers = new List<(string, string)> {
("Id", "Идентификатор"),
("", "Личные данные"),
("Login", "Логин"),
("Email", "Эл. почта"),
("InterestName", "Выбранный интерес")
};
wordTableComponentAccount.createWithTable(path, "Список аккаунтов", merges, widths, headers, _logic.ReadList(null));
}
} }
} }

View File

@ -60,4 +60,16 @@
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value> <value>17, 17</value>
</metadata> </metadata>
<metadata name="excelImagesComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>162, 27</value>
</metadata>
<metadata name="wordTableComponentAccount.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>378, 27</value>
</metadata>
<metadata name="componentDocumentWithChartBarPdf.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>639, 27</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>90</value>
</metadata>
</root> </root>

View File

@ -17,10 +17,8 @@ namespace AccountsContracts.BindingModels
public int Id { get; set; } public int Id { get; set; }
public Dictionary<int, IInterestModel> AccountInterests public int InterestId { get; set; }
{
get; public string Avatar { get; set; }
set;
} = new();
} }
} }

View File

@ -17,5 +17,8 @@ namespace AccountsContracts.ViewModels
[DisplayName("Электронная почта")] [DisplayName("Электронная почта")]
public string Email { get; set; } = string.Empty; public string Email { get; set; } = string.Empty;
public int Id { get; set; } public int Id { get; set; }
public int InterestId { get; set; }
public string InterestName { get; set; } = string.Empty;
public string Avatar { get; set; } = string.Empty;
} }
} }

View File

@ -19,4 +19,8 @@
<ProjectReference Include="..\AccountsContracts\AccountsContracts.csproj" /> <ProjectReference Include="..\AccountsContracts\AccountsContracts.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project> </Project>

View File

@ -15,6 +15,5 @@ namespace AccountsDataBaseImplement
public virtual DbSet<Account> Accounts { set; get; } public virtual DbSet<Account> Accounts { set; get; }
public virtual DbSet<Interest> Interests { set; get; } public virtual DbSet<Interest> Interests { set; get; }
public virtual DbSet<AccountInterest> AccountInterests { set; get; }
} }
} }

View File

@ -18,8 +18,7 @@ namespace AccountsDataBaseImplement.Implements
{ {
using var context = new AccountsDatabase(); using var context = new AccountsDatabase();
return context.Accounts return context.Accounts
.Include(x => x.Interests) .Include(x => x.Interest)
.ThenInclude(x => x.Interest)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
@ -32,8 +31,7 @@ namespace AccountsDataBaseImplement.Implements
using var context = new AccountsDatabase(); using var context = new AccountsDatabase();
return context.Accounts return context.Accounts
.Include(x => x.Interests) .Include(x => x.Interest)
.ThenInclude(x => x.Interest)
.Where(x => x.Id == model.Id) .Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
@ -47,19 +45,18 @@ namespace AccountsDataBaseImplement.Implements
using var context = new AccountsDatabase(); using var context = new AccountsDatabase();
return context.Accounts return context.Accounts
.Include(x => x.Interests) .Include(x => x.Interest)
.ThenInclude(x => x.Interest)
.FirstOrDefault(x => x.Id == model.Id) .FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel; ?.GetViewModel;
} }
public AccountViewModel? Insert(AccountBindingModel model) public AccountViewModel? Insert(AccountBindingModel model)
{ {
var newAccount = Account.Create(model); using var context = new AccountsDatabase();
var newAccount = Account.Create(context, model);
if (newAccount == null) if (newAccount == null)
{ {
return null; return null;
} }
using var context = new AccountsDatabase();
context.Accounts.Add(newAccount); context.Accounts.Add(newAccount);
context.SaveChanges(); context.SaveChanges();
return newAccount.GetViewModel; return newAccount.GetViewModel;
@ -72,7 +69,7 @@ namespace AccountsDataBaseImplement.Implements
{ {
return null; return null;
} }
account.Update(model); account.Update(model, context);
context.SaveChanges(); context.SaveChanges();
return account.GetViewModel; return account.GetViewModel;
} }
@ -80,7 +77,7 @@ namespace AccountsDataBaseImplement.Implements
{ {
using var context = new AccountsDatabase(); using var context = new AccountsDatabase();
var element = context.Accounts var element = context.Accounts
.Include(x => x.Interests) .Include(x => x.Interest)
.FirstOrDefault(rec => rec.Id == model.Id); .FirstOrDefault(rec => rec.Id == model.Id);
if (element != null) if (element != null)
{ {

View File

@ -11,7 +11,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace AccountsDataBaseImplement.Migrations namespace AccountsDataBaseImplement.Migrations
{ {
[DbContext(typeof(AccountsDatabase))] [DbContext(typeof(AccountsDatabase))]
[Migration("20231116164358_InitialCreate")] [Migration("20231129182743_InitialCreate")]
partial class InitialCreate partial class InitialCreate
{ {
/// <inheritdoc /> /// <inheritdoc />
@ -36,6 +36,9 @@ namespace AccountsDataBaseImplement.Migrations
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
b.Property<int>("InterestId")
.HasColumnType("integer");
b.Property<string>("Login") b.Property<string>("Login")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
@ -46,30 +49,9 @@ namespace AccountsDataBaseImplement.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Accounts");
});
modelBuilder.Entity("AccountsDataBaseImplement.Models.AccountInterest", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("AccountId")
.HasColumnType("integer");
b.Property<int>("InterestId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("InterestId"); b.HasIndex("InterestId");
b.ToTable("AccountInterests"); b.ToTable("Accounts");
}); });
modelBuilder.Entity("AccountsDataBaseImplement.Models.Interest", b => modelBuilder.Entity("AccountsDataBaseImplement.Models.Interest", b =>
@ -89,29 +71,16 @@ namespace AccountsDataBaseImplement.Migrations
b.ToTable("Interests"); b.ToTable("Interests");
}); });
modelBuilder.Entity("AccountsDataBaseImplement.Models.AccountInterest", b => modelBuilder.Entity("AccountsDataBaseImplement.Models.Account", b =>
{ {
b.HasOne("AccountsDataBaseImplement.Models.Account", "Account")
.WithMany("Interests")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AccountsDataBaseImplement.Models.Interest", "Interest") b.HasOne("AccountsDataBaseImplement.Models.Interest", "Interest")
.WithMany() .WithMany()
.HasForeignKey("InterestId") .HasForeignKey("InterestId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("Account");
b.Navigation("Interest"); b.Navigation("Interest");
}); });
modelBuilder.Entity("AccountsDataBaseImplement.Models.Account", b =>
{
b.Navigation("Interests");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@ -11,21 +11,6 @@ namespace AccountsDataBaseImplement.Migrations
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.CreateTable(
name: "Accounts",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Login = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Accounts", x => x.Id);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "Interests", name: "Interests",
columns: table => new columns: table => new
@ -40,25 +25,21 @@ namespace AccountsDataBaseImplement.Migrations
}); });
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "AccountInterests", name: "Accounts",
columns: table => new columns: table => new
{ {
Id = table.Column<int>(type: "integer", nullable: false) Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
AccountId = table.Column<int>(type: "integer", nullable: false), Login = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
InterestId = table.Column<int>(type: "integer", nullable: false) InterestId = table.Column<int>(type: "integer", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_AccountInterests", x => x.Id); table.PrimaryKey("PK_Accounts", x => x.Id);
table.ForeignKey( table.ForeignKey(
name: "FK_AccountInterests_Accounts_AccountId", name: "FK_Accounts_Interests_InterestId",
column: x => x.AccountId,
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AccountInterests_Interests_InterestId",
column: x => x.InterestId, column: x => x.InterestId,
principalTable: "Interests", principalTable: "Interests",
principalColumn: "Id", principalColumn: "Id",
@ -66,22 +47,14 @@ namespace AccountsDataBaseImplement.Migrations
}); });
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_AccountInterests_AccountId", name: "IX_Accounts_InterestId",
table: "AccountInterests", table: "Accounts",
column: "AccountId");
migrationBuilder.CreateIndex(
name: "IX_AccountInterests_InterestId",
table: "AccountInterests",
column: "InterestId"); column: "InterestId");
} }
/// <inheritdoc /> /// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropTable(
name: "AccountInterests");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Accounts"); name: "Accounts");

View File

@ -0,0 +1,91 @@
// <auto-generated />
using AccountsDataBaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AccountsDataBaseImplement.Migrations
{
[DbContext(typeof(AccountsDatabase))]
[Migration("20231129200602_AddColumnAvatarToAccountTable")]
partial class AddColumnAvatarToAccountTable
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AccountsDataBaseImplement.Models.Account", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Avatar")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<int>("InterestId")
.HasColumnType("integer");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("InterestId");
b.ToTable("Accounts");
});
modelBuilder.Entity("AccountsDataBaseImplement.Models.Interest", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Interests");
});
modelBuilder.Entity("AccountsDataBaseImplement.Models.Account", b =>
{
b.HasOne("AccountsDataBaseImplement.Models.Interest", "Interest")
.WithMany()
.HasForeignKey("InterestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Interest");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AccountsDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class AddColumnAvatarToAccountTable : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Avatar",
table: "Accounts",
type: "text",
nullable: false,
defaultValue: "");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Avatar",
table: "Accounts");
}
}
}

View File

@ -29,10 +29,17 @@ namespace AccountsDataBaseImplement.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id")); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Avatar")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email") b.Property<string>("Email")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
b.Property<int>("InterestId")
.HasColumnType("integer");
b.Property<string>("Login") b.Property<string>("Login")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
@ -43,30 +50,9 @@ namespace AccountsDataBaseImplement.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Accounts");
});
modelBuilder.Entity("AccountsDataBaseImplement.Models.AccountInterest", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("AccountId")
.HasColumnType("integer");
b.Property<int>("InterestId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("InterestId"); b.HasIndex("InterestId");
b.ToTable("AccountInterests"); b.ToTable("Accounts");
}); });
modelBuilder.Entity("AccountsDataBaseImplement.Models.Interest", b => modelBuilder.Entity("AccountsDataBaseImplement.Models.Interest", b =>
@ -86,29 +72,16 @@ namespace AccountsDataBaseImplement.Migrations
b.ToTable("Interests"); b.ToTable("Interests");
}); });
modelBuilder.Entity("AccountsDataBaseImplement.Models.AccountInterest", b => modelBuilder.Entity("AccountsDataBaseImplement.Models.Account", b =>
{ {
b.HasOne("AccountsDataBaseImplement.Models.Account", "Account")
.WithMany("Interests")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AccountsDataBaseImplement.Models.Interest", "Interest") b.HasOne("AccountsDataBaseImplement.Models.Interest", "Interest")
.WithMany() .WithMany()
.HasForeignKey("InterestId") .HasForeignKey("InterestId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("Account");
b.Navigation("Interest"); b.Navigation("Interest");
}); });
modelBuilder.Entity("AccountsDataBaseImplement.Models.Account", b =>
{
b.Navigation("Interests");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@ -22,24 +22,14 @@ namespace AccountsDataBaseImplement.Models
public int Id { get; private set; } public int Id { get; private set; }
private Dictionary<int, IInterestModel>? _accountInterests = null; public int InterestId { get; set; }
[NotMapped]
public Dictionary<int, IInterestModel> AccountInterests
{
get
{
if (_accountInterests == null)
{
_accountInterests = Interests
.ToDictionary(recPI => recPI.InterestId, recPI => recPI.Interest as IInterestModel);
}
return _accountInterests;
}
}
[ForeignKey("AccountId")]
public virtual List<AccountInterest> Interests { get; set; } = new();
public static Account? Create(AccountBindingModel? model) public virtual Interest Interest { get; set; } = new();
[Required]
public string Avatar { get; set; } = string.Empty;
public static Account? Create(AccountsDatabase context, AccountBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
@ -51,19 +41,13 @@ namespace AccountsDataBaseImplement.Models
Login = model.Login, Login = model.Login,
Password = model.Password, Password = model.Password,
Email = model.Email, Email = model.Email,
InterestId = model.InterestId,
Interest = context.Interests.First(x => x.Id == model.InterestId),
Avatar = model.Avatar,
}; };
} }
public static Account? Create(AccountViewModel? model)
{ public void Update(AccountBindingModel? model, AccountsDatabase context)
return new Account()
{
Id = model.Id,
Login = model.Login,
Password = model.Password,
Email = model.Email,
};
}
public void Update(AccountBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
@ -71,39 +55,20 @@ namespace AccountsDataBaseImplement.Models
} }
Login = model.Login; Login = model.Login;
Password = model.Password; Password = model.Password;
InterestId = model.InterestId;
Interest = context.Interests.First(x => x.Id == model.InterestId);
Avatar = model.Avatar;
} }
public AccountViewModel GetViewModel => new() public AccountViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
Login = Login, Login = Login,
Password = Password, Password = Password,
Email = Email, Email = Email,
InterestId = InterestId,
InterestName = Interest.Name,
Avatar = Avatar,
}; };
public void UpdateInterests(AccountsDatabase context, AccountBindingModel model)
{
var accountInterests = context.AccountInterests.Where(rec => rec.AccountId == model.Id).ToList();
if (accountInterests != null && accountInterests.Count > 0)
{
// удалили те, которых нет в модели
context.AccountInterests.RemoveRange(accountInterests.Where(rec => !model.AccountInterests.ContainsKey(rec.InterestId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateInterest in accountInterests)
{
model.AccountInterests.Remove(updateInterest.InterestId);
}
var account = context.Accounts.First(x => x.Id == Id);
foreach (var pc in model.AccountInterests)
{
context.AccountInterests.Add(new AccountInterest
{
Account = account,
Interest = context.Interests.First(x => x.Id == pc.Key),
});
context.SaveChanges();
}
_accountInterests = null;
}
}
} }
} }

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccountsDataBaseImplement.Models
{
public class AccountInterest
{
public int Id { get; set; }
[Required]
public int AccountId { get; set; }
[Required]
public int InterestId { get; set; }
public virtual Account Account { get; set; } = new();
public virtual Interest Interest { get; set; } = new();
}
}

View File

@ -11,5 +11,7 @@ namespace AccountsDataModels.Models
string Login { get; } string Login { get; }
string Password { get; } string Password { get; }
string Email { get; } string Email { get; }
public int InterestId { get; }
public string Avatar { get; }
} }
} }