Finished CRUD part

This commit is contained in:
abazov73 2023-11-29 23:40:28 +04:00
parent c44012c58c
commit c3d19cda92
18 changed files with 357 additions and 218 deletions

View File

@ -19,6 +19,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AbazovViewComponents\AbazovViewComponents.csproj" />
<ProjectReference Include="..\AccountsBusinessLogic\AccountsBusinessLogic.csproj" />
<ProjectReference Include="..\AccountsDataBaseImplement\AccountsDataBaseImplement.csproj" />
</ItemGroup>

View File

@ -28,19 +28,148 @@
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAccount));
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.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, 195);
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, 172);
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, 364);
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, 364);
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);
//
// FormAccount
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.ClientSize = new System.Drawing.Size(413, 405);
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.Text = "Аккаунт";
this.Load += new System.EventHandler(this.FormAccount_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#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;
}
}

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.ComponentModel;
using System.Data;
@ -12,9 +17,98 @@ namespace AccountsApp
{
public partial class FormAccount : Form
{
public FormAccount()
private int? _id;
private readonly IAccountLogic _logic;
private readonly IInterestLogic _interestLogic;
private List<InterestViewModel> _interests;
public int Id { set { _id = value; } }
public FormAccount(IAccountLogic logic, IInterestLogic interestLogic)
{
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;
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;
}
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
};
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);
}
}
}
}

View File

@ -57,4 +57,12 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="abazovCheckedListBox.selectedItems" mimetype="application/x-microsoft.net.object.binary.base64">
<value>
AAEAAAD/////AQAAAAAAAAAEAQAAAH9TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5
c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVi
bGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24GAAAI
CAkCAAAAAAAAAAAAAAARAgAAAAAAAAAL
</value>
</data>
</root>

View File

@ -28,7 +28,6 @@
/// </summary>
private void InitializeComponent()
{
this.controlDataTableAccounts = new ControlsLibraryNet60.Data.ControlDataTableTable();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.аккаунтыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.создатьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
@ -39,19 +38,10 @@
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.menuStrip1.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
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
@ -89,6 +79,7 @@
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.Text = "Редактировать";
this.редактироватьToolStripMenuItem.Click += new System.EventHandler(this.редактироватьToolStripMenuItem_Click);
//
// удалитьToolStripMenuItem
//
@ -96,6 +87,7 @@
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.Text = "Удалить";
this.удалитьToolStripMenuItem.Click += new System.EventHandler(this.удалитьToolStripMenuItem_Click);
//
// отчётыToolStripMenuItem
//
@ -135,16 +127,27 @@
this.интересыToolStripMenuItem.Text = "Интересы";
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
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.controlDataTableAccounts);
this.Controls.Add(this.controlDataTable);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMain";
this.Text = "Аккаунты";
this.Load += new System.EventHandler(this.FormMain_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
@ -153,8 +156,6 @@
}
#endregion
private ControlsLibraryNet60.Data.ControlDataTableTable controlDataTableAccounts;
private MenuStrip menuStrip1;
private ToolStripMenuItem аккаунтыToolStripMenuItem;
private ToolStripMenuItem создатьToolStripMenuItem;
@ -165,5 +166,6 @@
private ToolStripMenuItem документСТаблицейToolStripMenuItem;
private ToolStripMenuItem документСДиаграммойToolStripMenuItem;
private ToolStripMenuItem интересыToolStripMenuItem;
private ControlsLibraryNet60.Data.ControlDataTableTable controlDataTable;
}
}

View File

@ -1,4 +1,9 @@
using System;
using AccountsContracts.BindingModels;
using AccountsContracts.BusinessLogicContracts;
using AccountsContracts.ViewModels;
using ControlsLibraryNet60.Core;
using ControlsLibraryNet60.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -12,9 +17,18 @@ namespace AccountsApp
{
public partial class FormMain : Form
{
public FormMain()
private IAccountLogic _logic;
public FormMain(IAccountLogic logic)
{
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},
});
}
private void создатьToolStripMenuItem_Click(object sender, EventArgs e)
@ -24,7 +38,7 @@ namespace AccountsApp
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
@ -37,5 +51,44 @@ namespace AccountsApp
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();
}
}
}
}
}

View File

@ -60,4 +60,7 @@
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -33,6 +33,9 @@ namespace AccountsDataBaseImplement.Migrations
.IsRequired()
.HasColumnType("text");
b.Property<int>("InterestId")
.HasColumnType("integer");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
@ -43,30 +46,9 @@ namespace AccountsDataBaseImplement.Migrations
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.ToTable("AccountInterests");
b.ToTable("Accounts");
});
modelBuilder.Entity("AccountsDataBaseImplement.Models.Interest", b =>
@ -86,29 +68,16 @@ namespace AccountsDataBaseImplement.Migrations
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")
.WithMany()
.HasForeignKey("InterestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
b.Navigation("Interest");
});
modelBuilder.Entity("AccountsDataBaseImplement.Models.Account", b =>
{
b.Navigation("Interests");
});
#pragma warning restore 612, 618
}
}

View File

@ -22,24 +22,11 @@ namespace AccountsDataBaseImplement.Models
public int Id { get; private set; }
private Dictionary<int, IInterestModel>? _accountInterests = null;
[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 int InterestId { get; set; }
public static Account? Create(AccountBindingModel? model)
public virtual Interest Interest { get; set; } = new();
public static Account? Create(AccountsDatabase context, AccountBindingModel? model)
{
if (model == null)
{
@ -51,19 +38,12 @@ namespace AccountsDataBaseImplement.Models
Login = model.Login,
Password = model.Password,
Email = model.Email,
InterestId = model.InterestId,
Interest = context.Interests.First(x => x.Id == model.InterestId),
};
}
public static Account? Create(AccountViewModel? model)
{
return new Account()
{
Id = model.Id,
Login = model.Login,
Password = model.Password,
Email = model.Email,
};
}
public void Update(AccountBindingModel? model)
public void Update(AccountBindingModel? model, AccountsDatabase context)
{
if (model == null)
{
@ -71,39 +51,18 @@ namespace AccountsDataBaseImplement.Models
}
Login = model.Login;
Password = model.Password;
InterestId = model.InterestId;
Interest = context.Interests.First(x => x.Id == model.InterestId);
}
public AccountViewModel GetViewModel => new()
{
Id = Id,
Login = Login,
Password = Password,
Email = Email,
InterestId = InterestId,
InterestName = Interest.Name,
};
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,6 @@ namespace AccountsDataModels.Models
string Login { get; }
string Password { get; }
string Email { get; }
public int InterestId { get; }
}
}