ISEbd-22 Musatkina K. Y. Lab work 5 HARD #23

Closed
Kristina wants to merge 5 commits from 5hardlaba into lab5base
23 changed files with 1613 additions and 90 deletions
Showing only changes of commit 3133183539 - Show all commits

View File

@ -85,38 +85,33 @@ namespace BlacksmithWorkshopFileImplement.Implements
}
return null;
}
//проверка колва
private bool CheckAvailability(int ManufactureId, int count)
private bool CheckSell(int ManufactureId, int count)
{
count -= _source.Shops.Select(x => x.ShopManufactures.Select(y =>
(y.Value.Item1.Id == ManufactureId ? y.Value.Item2 : 0)).Sum()).Sum();
return count <= 0;
}
//операция продажи изделий
public bool SellManufactures(IManufactureModel model, int count)
{
var neededManufacture = _source.Manufactures.FirstOrDefault(x => x.Id == model.Id);
if (neededManufacture == null || !CheckAvailability(neededManufacture.Id, count))//наличие необходимого изделия для продажи и его доступность
if (neededManufacture == null || !CheckSell(neededManufacture.Id, count))
{
return false;
}
for (int i = 0; i < _source.Shops.Count; i++)
{
var shop = _source.Shops[i];
var assortment = shop.ShopManufactures;//Получаем ассортимент
foreach (var manufacture in assortment.Where(x => x.Value.Item1.Id == neededManufacture.Id))//выбираем изделия с нужным Id.
var assortment = shop.ShopManufactures;
foreach (var manufacture in assortment.Where(x => x.Value.Item1.Id == neededManufacture.Id))
{
//Продаем выбранное количество изделий, уменьшая количество доступных товаров в ассортименте магазина.
var min = Math.Min(manufacture.Value.Item2, count);//мин колво данного изделия для продажи
//уменьшаем количество доступных для продажи изделия на количество проданных
var min = Math.Min(manufacture.Value.Item2, count);
assortment[manufacture.Value.Item1.Id] = (manufacture.Value.Item1, manufacture.Value.Item2 - min);
count -= min;//Уменьшаем общее количество единиц для продажи
count -= min;
if (count <= 0)
{
break;
}
}
//Обновляем информацию
shop.Update(new ShopBindingModel
{
Id = shop.Id,

View File

@ -13,7 +13,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopBusinessL
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopListImplement", "BlacksmithWorkshopListImplement\BlacksmithWorkshopListImplement.csproj", "{F6B2AA66-2A89-4DEA-AE90-84991C1EE424}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopFileImplement", "BlackcmithWorkshopFileImplement\BlacksmithWorkshopFileImplement.csproj", "{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopFileImplement", "BlackcmithWorkshopFileImplement\BlacksmithWorkshopFileImplement.csproj", "{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopDatabaseImplement", "BlacksmithWorkshopDatabaseImplement\BlacksmithWorkshopDatabaseImplement.csproj", "{07550D11-E516-44E1-88A4-5B21E3EE72CC}"
ProjectSection(ProjectDependencies) = postProject
{40A50297-20F6-4F73-834D-0902F6F7965B} = {40A50297-20F6-4F73-834D-0902F6F7965B}
{96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC} = {96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -45,6 +51,10 @@ Global
{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}.Release|Any CPU.Build.0 = Release|Any CPU
{07550D11-E516-44E1-88A4-5B21E3EE72CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{07550D11-E516-44E1-88A4-5B21E3EE72CC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07550D11-E516-44E1-88A4-5B21E3EE72CC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07550D11-E516-44E1-88A4-5B21E3EE72CC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -9,12 +9,17 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlackcmithWorkshopFileImplement\BlacksmithWorkshopFileImplement.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopBusinessLogic\BlacksmithWorkshopBusinessLogic.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopDatabaseImplement\BlacksmithWorkshopDatabaseImplement.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopListImplement\BlacksmithWorkshopListImplement.csproj" />
</ItemGroup>

View File

@ -75,32 +75,14 @@ namespace BlacksmithWorkshop
}
private OrderBindingModel CreateBindingModel(int id, bool isDone = false)
{
String? status = dataGridView.SelectedRows[0].Cells["Status"].Value.ToString();
String? sum = dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString();
String? dateCreate = dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString();
if (status == null)
{
MessageBox.Show("Ошибка при создании модели");
throw new ArgumentNullException(nameof(status));
}
if (sum == null)
{
MessageBox.Show("Ошибка при создании модели");
throw new ArgumentNullException(nameof(sum));
}
if (dateCreate == null)
{
MessageBox.Show("Ошибка при создании модели");
throw new ArgumentNullException(nameof(dateCreate));
}
return new OrderBindingModel
{
Id = id,
ManufactureId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ManufactureId"].Value),
Status = Enum.Parse<OrderStatus>(status),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(sum),
DateCreate = DateTime.Parse(dateCreate),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
};
}
private void TakeInWorkButton_Click(object sender, EventArgs e)

View File

@ -38,47 +38,43 @@
//
// ManufactureComboBox
//
ManufactureComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
ManufactureComboBox.FormattingEnabled = true;
ManufactureComboBox.Location = new Point(141, 20);
ManufactureComboBox.Margin = new Padding(4, 5, 4, 5);
ManufactureComboBox.Location = new Point(99, 12);
ManufactureComboBox.Name = "ManufactureComboBox";
ManufactureComboBox.Size = new Size(171, 33);
ManufactureComboBox.Size = new Size(121, 23);
ManufactureComboBox.TabIndex = 0;
//
// ManufactureLabel
//
ManufactureLabel.AutoSize = true;
ManufactureLabel.Location = new Point(17, 33);
ManufactureLabel.Margin = new Padding(4, 0, 4, 0);
ManufactureLabel.Location = new Point(12, 20);
ManufactureLabel.Name = "ManufactureLabel";
ManufactureLabel.Size = new Size(80, 25);
ManufactureLabel.Size = new Size(53, 15);
ManufactureLabel.TabIndex = 1;
ManufactureLabel.Text = "Изделие";
//
// CountLabel
//
CountLabel.AutoSize = true;
CountLabel.Location = new Point(19, 82);
CountLabel.Margin = new Padding(4, 0, 4, 0);
CountLabel.Location = new Point(21, 49);
CountLabel.Name = "CountLabel";
CountLabel.Size = new Size(107, 25);
CountLabel.Size = new Size(72, 15);
CountLabel.TabIndex = 2;
CountLabel.Text = "Количество";
//
// CountTextBox
//
CountTextBox.Location = new Point(141, 68);
CountTextBox.Margin = new Padding(4, 5, 4, 5);
CountTextBox.Location = new Point(99, 41);
CountTextBox.Name = "CountTextBox";
CountTextBox.Size = new Size(171, 31);
CountTextBox.Size = new Size(121, 23);
CountTextBox.TabIndex = 3;
//
// ButtonSave
//
ButtonSave.Location = new Point(91, 122);
ButtonSave.Margin = new Padding(4, 5, 4, 5);
ButtonSave.Location = new Point(64, 73);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(107, 38);
ButtonSave.Size = new Size(75, 23);
ButtonSave.TabIndex = 4;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
@ -86,10 +82,9 @@
//
// ButtonCancel
//
ButtonCancel.Location = new Point(207, 122);
ButtonCancel.Margin = new Padding(4, 5, 4, 5);
ButtonCancel.Location = new Point(145, 73);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(107, 38);
ButtonCancel.Size = new Size(75, 23);
ButtonCancel.TabIndex = 5;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
@ -97,17 +92,17 @@
//
// FormSell
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(320, 180);
ClientSize = new Size(224, 108);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Controls.Add(CountTextBox);
Controls.Add(CountLabel);
Controls.Add(ManufactureLabel);
Controls.Add(ManufactureComboBox);
Margin = new Padding(4, 5, 4, 5);
Name = "FormSell";
StartPosition = FormStartPosition.CenterParent;
Text = "Форма продажи";
ResumeLayout(false);
PerformLayout();

View File

@ -1,6 +1,7 @@
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -61,46 +62,37 @@ namespace BlacksmithWorkshop
return null;
}
}
//количество изделий для продажи
public int Count
{
get { return Convert.ToInt32(CountTextBox.Text); }
set
{ CountTextBox.Text = value.ToString(); }
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(CountTextBox.Text))
{
//если пустое
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//если пустое
if (ManufactureComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка",
MessageBox.Show("Выберите кузнечное изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
int count = Convert.ToInt32(CountTextBox.Text);//количество изделий, которые будут проданы
var manufacture = _manufactureLogic.ReadElement(new() { Id = Convert.ToInt32(ManufactureComboBox.SelectedValue) });//инф о выбранном издели для продажи
int count = Convert.ToInt32(CountTextBox.Text);
var manufacture = _manufactureLogic.ReadElement(new() { Id = Convert.ToInt32(ManufactureComboBox.SelectedValue) });
if (manufacture == null)
{
MessageBox.Show("Ошибка при продаже.");
return;
throw new ApplicationException("Ошибка при продаже. Ошибка получения данных об элементе.");
}
bool res = _shopLogic.SellManufactures(manufacture, count);//отвечает за продажу изделий из магазина
// Если операция продажи не была успешной
if (!res)
if (!_shopLogic.SellManufactures(manufacture, count))
{
throw new Exception("Ошибка при продаже.");
throw new ApplicationException("Ошибка при продаже. Недостаточно изделий данного типа в магазинах.");
}
MessageBox.Show("Продажа прошла успешно");
DialogResult = DialogResult.OK;
@ -108,11 +100,10 @@ namespace BlacksmithWorkshop
}
catch (Exception)
{
MessageBox.Show("Ошибка продажи");
MessageBox.Show("Ошибка при продаже.");
return;
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;

View File

@ -1,7 +1,7 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogics;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopFileImplement.Implements;
using BlacksmithWorkshopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
@ -37,21 +37,21 @@ namespace BlacksmithWorkshop
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IManufactureStorage, ManufactureStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IManufactureLogic, ManufactureLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormManufacture>();
services.AddTransient<FormManufactures>();
services.AddTransient<FormManufactureComponent>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormSupply>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormSupply>();
services.AddTransient<FormSell>();
}
}

View File

@ -77,8 +77,6 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics
}
return true;
}
//наполненность магазина
public bool ReplenishManufactures(ShopSearchModel model, IManufactureModel manufacture, int count)
{
_logger.LogInformation("Try to replenish manufactures. ShopName:{ShopName}. Id:{Id}", model.ShopName, model.Id);
@ -103,25 +101,19 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics
_logger.LogWarning("Read operation failed");
throw new ArgumentException("Количество должно быть положительным");
}
//общее количество предметов в магазине
int countItems = curModel.ShopManufactures.Select(x => x.Value.Item2).Sum();
//проверка
if (curModel.MaxCapacity - countItems >= count)//если места достаточно
if (curModel.MaxCapacity - countItems >= count)
{
if (curModel.ShopManufactures.TryGetValue(manufacture.Id, out var sameDocument))
{
curModel.ShopManufactures[manufacture.Id] = (manufacture, sameDocument.Item2 + count);//если есть такое, то +1
//логирование о том, что было найдено уже существующее производство //логирование информации о том, что было найдено уже существующее производство
curModel.ShopManufactures[manufacture.Id] = (manufacture, sameDocument.Item2 + count);
_logger.LogInformation("Same manufacture found by supply. Added {0} of {1} in {2} shop", count, manufacture.ManufactureName, curModel.ShopName);
}
else
{
curModel.ShopManufactures[manufacture.Id] = (manufacture, count);//просто добавляется
curModel.ShopManufactures[manufacture.Id] = (manufacture, count);
_logger.LogInformation("New manufacture added by supply. Added {0} of {1} in {2} shop", count, manufacture.ManufactureName, curModel.ShopName);
}
//обновление данных
_shopStorage.Update(new()
{
Id = curModel.Id,
@ -132,7 +124,6 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics
MaxCapacity = curModel.MaxCapacity
});
}
//если недостаточно места - предупреждение
else
{
_logger.LogWarning("Required shop is overflowed");

View File

@ -0,0 +1,28 @@
using BlacksmithWorkshopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement
{
public class BlacksmithWorkshopDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=BlacksmithWorkshopDataBaseHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Manufacture> Manufactures { set; get; }
public virtual DbSet<ManufactureComponent> ManufactureComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopManufacture> ShopManufactures { set; get; }
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,89 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDataBase();
return context.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel
model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
using var context = new BlacksmithWorkshopDataBase();
return context.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
.Select(x => x.GetViewModel)
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
return context.Components
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName ==
model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var component = context.Components.FirstOrDefault(x => x.Id ==
model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var element = context.Components.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,109 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class ManufactureStorage : IManufactureStorage
{
public List<ManufactureViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDataBase();
return context.Manufactures
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ManufactureViewModel> GetFilteredList(ManufactureSearchModel model)
{
if (string.IsNullOrEmpty(model.ManufactureName))
{
return new();
}
using var context = new BlacksmithWorkshopDataBase();
return context.Manufactures.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.ManufactureName.Contains(model.ManufactureName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public ManufactureViewModel? GetElement(ManufactureSearchModel model)
{
if (string.IsNullOrEmpty(model.ManufactureName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
return context.Manufactures
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ManufactureName) &&
x.ManufactureName == model.ManufactureName) ||
(model.Id.HasValue && x.Id ==
model.Id))
?.GetViewModel;
}
public ManufactureViewModel? Insert(ManufactureBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var newManufacture = Manufacture.Create(context, model);
if (newManufacture == null)
{
return null;
}
context.Manufactures.Add(newManufacture);
context.SaveChanges();
return newManufacture.GetViewModel;
}
public ManufactureViewModel? Update(ManufactureBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var manufacture = context.Manufactures.FirstOrDefault(rec =>
rec.Id == model.Id);
if (manufacture == null)
{
return null;
}
manufacture.Update(model);
context.SaveChanges();
manufacture.UpdateComponents(context, model);
transaction.Commit();
return manufacture.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ManufactureViewModel? Delete(ManufactureBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var element = context.Manufactures
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Manufactures.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,90 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDataBase();
return context.Orders
.Include(x => x.Manufacture)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new BlacksmithWorkshopDataBase();
return context.Orders
.Include(x => x.Manufacture)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
return context.Orders
.Include(x => x.Manufacture)
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
context.Orders.Add(newOrder);
context.SaveChanges();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var order = context.Orders
.Include(x => x.Manufacture)
.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var element = context.Orders
.Include(x => x.Manufacture)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,148 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var element = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Shops.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
return context.Shops
.Include(x => x.Manufactures)
.ThenInclude(x => x.Manufacture)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
using var context = new BlacksmithWorkshopDataBase();
return context.Shops
.Include(x => x.Manufactures)
.ThenInclude(x => x.Manufacture)
.Select(x => x.GetViewModel)
.Where(x => x.ShopName.Contains(model.ShopName ?? string.Empty))
.ToList();
}
public List<ShopViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDataBase();
return context.Shops
.Include(x => x.Manufactures)
.ThenInclude(x => x.Manufacture)
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
try
{
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
if (context.Shops.Any(x => x.ShopName == newShop.ShopName))
{
throw new Exception("Не должно быть два магазина с одним названием");
}
context.Shops.Add(newShop);
context.SaveChanges();
return newShop.GetViewModel;
}
catch
{
throw;
}
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
try
{
if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id)))
{
throw new Exception("Не должно быть два магазина с одним названием");
}
shop.Update(model);
shop.UpdateManufactures(context, model);
context.SaveChanges();
return shop.GetViewModel;
}
catch
{
throw;
}
}
public bool SellManufactures(IManufactureModel model, int count)
{
if (model == null)
return false;
using var context = new BlacksmithWorkshopDataBase();
using var transaction = context.Database.BeginTransaction();
List<ShopManufacture> lst = new List<ShopManufacture>();
foreach (var el in context.ShopManufactures.Where(x => x.ManufactureId == model.Id))
{
int dif = count;
if (el.Count < dif)
dif = el.Count;
el.Count -= dif;
count -= dif;
if (el.Count == 0)
{
lst.Add(el);
}
if (count == 0)
break;
}
if (count > 0)
{
transaction.Rollback();
return false;
}
foreach (var el in lst)
{
context.ShopManufactures.Remove(el);
}
context.SaveChanges();
transaction.Commit();
return true;
}
}
}

View File

@ -0,0 +1,250 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDataBase))]
[Migration("20240325175852_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.16")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ManufactureId");
b.ToTable("ManufactureComponents");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCapacity")
.HasColumnType("int");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("ShopId");
b.ToTable("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component")
.WithMany("ManufactureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Components")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("ShopManufactures")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Manufactures")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("Shop");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b =>
{
b.Navigation("ManufactureComponents");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
b.Navigation("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Manufactures");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,184 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ComponentName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Manufactures",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufactures", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShopName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
OpeningDate = table.Column<DateTime>(type: "datetime2", nullable: false),
MaxCapacity = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ManufactureComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureId = table.Column<int>(type: "int", nullable: false),
ComponentId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ManufactureComponents", x => x.Id);
table.ForeignKey(
name: "FK_ManufactureComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ManufactureComponents_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true),
ManufactureId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ShopManufactures",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureId = table.Column<int>(type: "int", nullable: false),
ShopId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopManufactures", x => x.Id);
table.ForeignKey(
name: "FK_ShopManufactures_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopManufactures_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ManufactureComponents_ComponentId",
table: "ManufactureComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_ManufactureComponents_ManufactureId",
table: "ManufactureComponents",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ManufactureId",
table: "Orders",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_ShopManufactures_ManufactureId",
table: "ShopManufactures",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_ShopManufactures_ShopId",
table: "ShopManufactures",
column: "ShopId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ManufactureComponents");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ShopManufactures");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Manufactures");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -0,0 +1,247 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDataBase))]
partial class BlacksmithWorkshopDataBaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.16")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ManufactureId");
b.ToTable("ManufactureComponents");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCapacity")
.HasColumnType("int");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("ShopId");
b.ToTable("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component")
.WithMany("ManufactureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Components")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("ShopManufactures")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Manufactures")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("Shop");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b =>
{
b.Navigation("ManufactureComponents");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
b.Navigation("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Manufactures");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,62 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
[Required]
public string ComponentName { get; private set; } = string.Empty;
[Required]
public double Cost { get; set; }
[ForeignKey("ComponentId")]
public virtual List<ManufactureComponent> ManufactureComponents { get; set; } =
new();
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component Create(ComponentViewModel model)
{
return new Component
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public void Update(ComponentBindingModel model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,104 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Manufacture : IManufactureModel
{
public int Id { get; set; }
[Required]
public string ManufactureName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _manufactureComponents =
null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> ManufactureComponents
{
get
{
if (_manufactureComponents == null)
{
_manufactureComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _manufactureComponents;
}
}
[ForeignKey("ManufactureId")]
public virtual List<ManufactureComponent> Components { get; set; } = new();
[ForeignKey("ManufactureId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ManufactureId")]
public virtual List<ShopManufacture> ShopManufactures { get; set; } = new();
public static Manufacture Create(BlacksmithWorkshopDataBase context,
ManufactureBindingModel model)
{
return new Manufacture()
{
Id = model.Id,
ManufactureName = model.ManufactureName,
Price = model.Price,
Components = model.ManufactureComponents.Select(x => new
ManufactureComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ManufactureBindingModel model)
{
ManufactureName = model.ManufactureName;
Price = model.Price;
}
public ManufactureViewModel GetViewModel => new()
{
Id = Id,
ManufactureName = ManufactureName,
Price = Price,
ManufactureComponents = ManufactureComponents
};
public void UpdateComponents(BlacksmithWorkshopDataBase context,
ManufactureBindingModel model)
{
var manufactureComponents = context.ManufactureComponents.Where(rec =>
rec.ManufactureId == model.Id).ToList();
if (manufactureComponents != null && ManufactureComponents.Count > 0)
{
context.ManufactureComponents.RemoveRange(manufactureComponents.Where(rec
=> !model.ManufactureComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
foreach (var updateComponent in manufactureComponents)
{
updateComponent.Count =
model.ManufactureComponents[updateComponent.ComponentId].Item2;
model.ManufactureComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var manufacture = context.Manufactures.First(x => x.Id == Id);
foreach (var pc in model.ManufactureComponents)
{
context.ManufactureComponents.Add(new ManufactureComponent
{
Manufacture = manufacture,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_manufactureComponents = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class ManufactureComponent
{
public int Id { get; set; }
[Required]
public int ManufactureId { get; set; }
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();
public virtual Manufacture Manufacture { get; set; } = new();
}
}

View File

@ -0,0 +1,64 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
[Required]
public int Count { get; private set; }
[Required]
public double Sum { get; private set; }
[Required]
public OrderStatus Status { get; private set; }
[Required]
public DateTime DateCreate { get; private set; }
public DateTime? DateImplement { get; private set; }
[Required]
public int ManufactureId { get; private set; }
public virtual Manufacture? Manufacture { get; set; }
public static Order Create(OrderBindingModel model)
{
return new Order()
{
Id = model.Id,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ManufactureId = model.ManufactureId,
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
ManufactureId = ManufactureId,
ManufactureName = Manufacture?.ManufactureName ?? string.Empty,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
};
}
}

View File

@ -0,0 +1,112 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
[Required]
public string ShopName { get; private set; } = string.Empty;
[Required]
public string Address { get; private set; } = string.Empty;
[Required]
public DateTime OpeningDate { get; private set; }
[Required]
public int MaxCapacity { get; private set; }
private Dictionary<int, (IManufactureModel, int)>? _ShopManufacture = null;
[NotMapped]
public Dictionary<int, (IManufactureModel, int)> ShopManufactures
{
get
{
if (_ShopManufacture == null)
{
_ShopManufacture = Manufactures
.ToDictionary(x => x.ManufactureId, x =>
(x.Manufacture as IManufactureModel, x.Count));
}
return _ShopManufacture;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopManufacture> Manufactures { get; set; } = new();
public static Shop? Create(BlacksmithWorkshopDataBase context, ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
OpeningDate = model.OpeningDate,
MaxCapacity = model.MaxCapacity,
Manufactures = model.ShopManufactures.Select(x => new ShopManufacture
{
Manufacture = context.Manufactures.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxCapacity = model.MaxCapacity;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
OpeningDate = OpeningDate,
ShopManufactures = ShopManufactures,
MaxCapacity = MaxCapacity
};
public void UpdateManufactures(BlacksmithWorkshopDataBase context, ShopBindingModel model)
{
var ShopManufacture = context.ShopManufactures.Where(rec =>
rec.ShopId == model.Id).ToList();
if (ShopManufacture != null && ShopManufacture.Count > 0)
{
context.ShopManufactures.RemoveRange(ShopManufacture.Where(rec
=> !model.ShopManufactures.ContainsKey(rec.ShopId)));
context.SaveChanges();
foreach (var updateManufacture in ShopManufacture)
{
updateManufacture.Count =
model.ShopManufactures[updateManufacture.ManufactureId].Item2;
model.ShopManufactures.Remove(updateManufacture.ManufactureId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var pc in model.ShopManufactures)
{
context.ShopManufactures.Add(new ShopManufacture
{
Shop = shop,
Manufacture = context.Manufactures.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_ShopManufacture = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class ShopManufacture
{
public int Id { get; set; }
[Required]
public int ManufactureId { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Manufacture Manufacture { get; set; } = new();
}
}