LabWork03_Basic

This commit is contained in:
parent 2bc1c46ea2
commit 60e7c05f06
15 changed files with 1368 additions and 1 deletions

View File

@ -15,6 +15,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AircraftPlantListImplement"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AircraftPlantFileImplement", "AircraftPlantFileImplement\AircraftPlantFileImplement.csproj", "{4456EC84-CEFC-419B-9A30-F1EE409120E4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AircraftPlantDatabaseImplement", "AircraftPlantDatabaseImplement\AircraftPlantDatabaseImplement.csproj", "{F10A6166-F5D7-4DE4-A991-19E7D51C624C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -45,6 +47,10 @@ Global
{4456EC84-CEFC-419B-9A30-F1EE409120E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4456EC84-CEFC-419B-9A30-F1EE409120E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4456EC84-CEFC-419B-9A30-F1EE409120E4}.Release|Any CPU.Build.0 = Release|Any CPU
{F10A6166-F5D7-4DE4-A991-19E7D51C624C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F10A6166-F5D7-4DE4-A991-19E7D51C624C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F10A6166-F5D7-4DE4-A991-19E7D51C624C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F10A6166-F5D7-4DE4-A991-19E7D51C624C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -0,0 +1,49 @@
using AircraftPlantDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftPlantDatabaseImplement
{
/// <summary>
/// Класс для взаимодействия с базой данных
/// </summary>
public class AircraftPlantDatabase : DbContext
{
/// <summary>
/// Подключение к базе данных
/// </summary>
/// <param name="optionsBuilder"></param>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=FACTORINO\SQLEXPRESS;Initial Catalog=AircraftPlantDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
/// <summary>
/// Таблица компонентов
/// </summary>
public virtual DbSet<Component> Components { set; get; }
/// <summary>
/// Таблица изделий
/// </summary>
public virtual DbSet<Plane> Planes { set; get; }
/// <summary>
/// Связь между изделиями и компонентами
/// </summary>
public virtual DbSet<PlaneComponent> PlaneComponents { set; get; }
/// <summary>
/// Таблица заказов
/// </summary>
public virtual DbSet<Order> Orders { 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.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AircraftPlantContracts\AircraftPlantContracts.csproj" />
<ProjectReference Include="..\AircraftPlantDataModels\AircraftPlantDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,127 @@
using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.SearchModels;
using AircraftPlantContracts.StoragesContracts;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftPlantDatabaseImplement.Implements
{
/// <summary>
/// Реализация интерфейса хранилища для компонентов
/// </summary>
public class ComponentStorage : IComponentStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<ComponentViewModel> GetFullList()
{
using var context = new AircraftPlantDatabase();
return context.Components
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
using var context = new AircraftPlantDatabase();
return context.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
using var context = new AircraftPlantDatabase();
return context.Components
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) &&
x.ComponentName == model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new AircraftPlantDatabase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new AircraftPlantDatabase();
var component = context.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new AircraftPlantDatabase();
var element = context.Components.FirstOrDefault(rec => rec.Id == model.Id);
if (element == null)
{
return null;
}
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
}
}

View File

@ -0,0 +1,140 @@
using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.SearchModels;
using AircraftPlantContracts.StoragesContracts;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftPlantDatabaseImplement.Implements
{
/// <summary>
/// Реализация интерфейса хранилища для заказов
/// </summary>
public class OrderStorage : IOrderStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<OrderViewModel> GetFullList()
{
using var context = new AircraftPlantDatabase();
return context.Orders
.Select(x => GetViewModel(x))
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new AircraftPlantDatabase();
return context.Orders
.Where(x => x.Id.Equals(model.Id))
.Select(x => GetViewModel(x))
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new AircraftPlantDatabase();
return GetViewModel(context.Orders
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)));
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new AircraftPlantDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return GetViewModel(newOrder);
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new AircraftPlantDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return GetViewModel(order);
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new AircraftPlantDatabase();
var element = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return GetViewModel(element);
}
return null;
}
/// <summary>
/// Получение модели заказа
/// </summary>
/// <param name="order"></param>
/// <returns></returns>
private static OrderViewModel GetViewModel(Order order)
{
using var context = new AircraftPlantDatabase();
var viewModel = order.GetViewModel;
var plane = context.Planes.FirstOrDefault(x => x.Id == order.PlaneId);
if (plane != null)
{
viewModel.PlaneName = plane.PlaneName;
}
return viewModel;
}
}
}

View File

@ -0,0 +1,148 @@
using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.SearchModels;
using AircraftPlantContracts.StoragesContracts;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftPlantDatabaseImplement.Implements
{
/// <summary>
/// Реализация интерфейса хранилища для изделий
/// </summary>
public class PlaneStorage : IPlaneStorage
{
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<PlaneViewModel> GetFullList()
{
using var context = new AircraftPlantDatabase();
return context.Planes
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<PlaneViewModel> GetFilteredList(PlaneSearchModel model)
{
if (string.IsNullOrEmpty(model.PlaneName))
{
return new();
}
using var context = new AircraftPlantDatabase();
return context.Planes
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.PlaneName.Contains(model.PlaneName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public PlaneViewModel? GetElement(PlaneSearchModel model)
{
if (string.IsNullOrEmpty(model.PlaneName) && !model.Id.HasValue)
{
return null;
}
using var context = new AircraftPlantDatabase();
return context.Planes
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.PlaneName) &&
x.PlaneName == model.PlaneName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public PlaneViewModel? Insert(PlaneBindingModel model)
{
using var context = new AircraftPlantDatabase();
var newPlane = Plane.Create(context, model);
if (newPlane == null)
{
return null;
}
context.Planes.Add(newPlane);
context.SaveChanges();
return newPlane.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public PlaneViewModel? Update(PlaneBindingModel model)
{
using var context = new AircraftPlantDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var plane = context.Planes.FirstOrDefault(rec => rec.Id == model.Id);
if (plane == null)
{
return null;
}
plane.Update(model);
context.SaveChanges();
plane.UpdateComponents(context, model);
transaction.Commit();
return plane.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public PlaneViewModel? Delete(PlaneBindingModel model)
{
using var context = new AircraftPlantDatabase();
var element = context.Planes
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Planes.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,169 @@
// <auto-generated />
using System;
using AircraftPlantDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace AircraftPlantDatabaseImplement.Migrations
{
[DbContext(typeof(AircraftPlantDatabase))]
[Migration("20240309195916_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("AircraftPlantDatabaseImplement.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("AircraftPlantDatabaseImplement.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>("PlaneId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("PlaneId");
b.ToTable("Orders");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PlaneName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Planes");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", 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>("PlaneId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("PlaneId");
b.ToTable("PlaneComponents");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", null)
.WithMany("Orders")
.HasForeignKey("PlaneId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b =>
{
b.HasOne("AircraftPlantDatabaseImplement.Models.Component", "Component")
.WithMany("PlaneComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane")
.WithMany("Components")
.HasForeignKey("PlaneId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Plane");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b =>
{
b.Navigation("PlaneComponents");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,125 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AircraftPlantDatabaseImplement.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: "Planes",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PlaneName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Planes", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PlaneId = table.Column<int>(type: "int", nullable: false),
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)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Planes_PlaneId",
column: x => x.PlaneId,
principalTable: "Planes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "PlaneComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PlaneId = 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_PlaneComponents", x => x.Id);
table.ForeignKey(
name: "FK_PlaneComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_PlaneComponents_Planes_PlaneId",
column: x => x.PlaneId,
principalTable: "Planes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_PlaneId",
table: "Orders",
column: "PlaneId");
migrationBuilder.CreateIndex(
name: "IX_PlaneComponents_ComponentId",
table: "PlaneComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_PlaneComponents_PlaneId",
table: "PlaneComponents",
column: "PlaneId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "PlaneComponents");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Planes");
}
}
}

View File

@ -0,0 +1,166 @@
// <auto-generated />
using System;
using AircraftPlantDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace AircraftPlantDatabaseImplement.Migrations
{
[DbContext(typeof(AircraftPlantDatabase))]
partial class AircraftPlantDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("AircraftPlantDatabaseImplement.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("AircraftPlantDatabaseImplement.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>("PlaneId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("PlaneId");
b.ToTable("Orders");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PlaneName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Planes");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", 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>("PlaneId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("PlaneId");
b.ToTable("PlaneComponents");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", null)
.WithMany("Orders")
.HasForeignKey("PlaneId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b =>
{
b.HasOne("AircraftPlantDatabaseImplement.Models.Component", "Component")
.WithMany("PlaneComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane")
.WithMany("Components")
.HasForeignKey("PlaneId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Plane");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b =>
{
b.Navigation("PlaneComponents");
});
modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,104 @@
using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AircraftPlantDatabaseImplement.Models
{
/// <summary>
/// Сущность "Компонент"
/// </summary>
public class Component : IComponentModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Название компонента
/// </summary>
[Required]
public string ComponentName { get; private set; } = string.Empty;
/// <summary>
/// Стоимость компонента
/// </summary>
[Required]
public double Cost { get; set; }
/// <summary>
/// Связь с классом связи изделия и компонента
/// </summary>
[ForeignKey("ComponentId")]
public virtual List<PlaneComponent> PlaneComponents { get; set; } = new();
/// <summary>
/// Создание модели компонента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
/// <summary>
/// Создание модели компонента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Component Create(ComponentViewModel model)
{
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
/// <summary>
/// Изменение модели компонента
/// </summary>
/// <param name="model"></param>
public void Update(ComponentBindingModel model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
/// <summary>
/// Получение модели компонента
/// </summary>
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,112 @@
using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDataModels.Enums;
using AircraftPlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftPlantDatabaseImplement.Models
{
/// <summary>
/// Сущность "Заказ"
/// </summary>
public class Order : IOrderModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Идентификатор изделия
/// </summary>
[Required]
public int PlaneId { get; set; }
/// <summary>
/// Количество изделий
/// </summary>
[Required]
public int Count { get; set; }
/// <summary>
/// Сумма заказа
/// </summary>
[Required]
public double Sum { get; set; }
/// <summary>
/// Статус заказа
/// </summary>
[Required]
public OrderStatus Status { get; set; }
/// <summary>
/// Дата создания заказа
/// </summary>
[Required]
public DateTime DateCreate { get; set; }
/// <summary>
/// Дата выполнения заказа
/// </summary>
public DateTime? DateImplement { get; set; }
/// <summary>
/// Создание модели заказа
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order
{
Id = model.Id,
PlaneId = model.PlaneId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
/// <summary>
/// Изменение модели заказа
/// </summary>
/// <param name="model"></param>
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
/// <summary>
/// Получение модели заказа
/// </summary>
public OrderViewModel GetViewModel => new()
{
Id = Id,
PlaneId = PlaneId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
}

View File

@ -0,0 +1,145 @@
using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDataModels.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 AircraftPlantDatabaseImplement.Models
{
/// <summary>
/// Сущность "Изделие"
/// </summary>
public class Plane : IPlaneModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Название изделия
/// </summary>
[Required]
public string PlaneName { get; set; } = string.Empty;
/// <summary>
/// Стоимость изделия
/// </summary>
[Required]
public double Price { get; set; }
/// <summary>
/// Коллекция компонентов изделия
/// </summary>
private Dictionary<int, (IComponentModel, int)>? _planeComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> PlaneComponents
{
get
{
if (_planeComponents == null)
{
_planeComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
}
return _planeComponents;
}
}
/// <summary>
/// Связь с классом связи изделия и компонента
/// </summary>
[ForeignKey("PlaneId")]
public virtual List<PlaneComponent> Components { get; set; } = new();
/// <summary>
/// Связь с заказами
/// </summary>
[ForeignKey("PlaneId")]
public virtual List<Order> Orders { get; set; } = new();
/// <summary>
/// Созданме модели изделия
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
/// <returns></returns>
public static Plane Create(AircraftPlantDatabase context, PlaneBindingModel model)
{
return new Plane()
{
Id = model.Id,
PlaneName = model.PlaneName,
Price = model.Price,
Components = model.PlaneComponents.Select(x => new PlaneComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
/// <summary>
/// Изменение модели изделия
/// </summary>
/// <param name="model"></param>
public void Update(PlaneBindingModel model)
{
PlaneName = model.PlaneName;
Price = model.Price;
}
/// <summary>
/// Получение модели изделия
/// </summary>
public PlaneViewModel GetViewModel => new()
{
Id = Id,
PlaneName = PlaneName,
Price = Price,
PlaneComponents = PlaneComponents
};
/// <summary>
/// Метод обновления списка связей
/// </summary>
/// <param name="context"></param>
/// <param name="model"></param>
public void UpdateComponents(AircraftPlantDatabase context, PlaneBindingModel model)
{
var planeComponents = context.PlaneComponents.Where(rec => rec.PlaneId == model.Id).ToList();
if (planeComponents != null && planeComponents.Count > 0)
{
// Удаление компонентов, которых нет в модели
context.PlaneComponents.RemoveRange(planeComponents.Where(rec => !model.PlaneComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// Обновление количества у существующих записей
foreach (var updateComponent in planeComponents)
{
updateComponent.Count = model.PlaneComponents[updateComponent.ComponentId].Item2;
model.PlaneComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var plane = context.Planes.First(x => x.Id == Id);
foreach (var pc in model.PlaneComponents)
{
context.PlaneComponents.Add(new PlaneComponent
{
Plane = plane,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_planeComponents = null;
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftPlantDatabaseImplement.Models
{
/// <summary>
/// Класс для связи изделия и компонента
/// </summary>
public class PlaneComponent
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; set; }
/// <summary>
/// Идентификатор изделия
/// </summary>
[Required]
public int PlaneId { get; set; }
/// <summary>
/// Идентификатор компонента
/// </summary>
[Required]
public int ComponentId { get; set; }
/// <summary>
/// Количество компонентов
/// </summary>
[Required]
public int Count { get; set; }
/// <summary>
/// Компонент
/// </summary>
public virtual Component Component { get; set; } = new();
/// <summary>
/// Изделие
/// </summary>
public virtual Plane Plane { get; set; } = new();
}
}

View File

@ -19,6 +19,10 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
@ -27,6 +31,7 @@
<ItemGroup>
<ProjectReference Include="..\AircraftPlantBusinessLogic\AircraftPlantBusinessLogic.csproj" />
<ProjectReference Include="..\AircraftPlantContracts\AircraftPlantContracts.csproj" />
<ProjectReference Include="..\AircraftPlantDatabaseImplement\AircraftPlantDatabaseImplement.csproj" />
<ProjectReference Include="..\AircraftPlantFileImplement\AircraftPlantFileImplement.csproj" />
<ProjectReference Include="..\AircraftPlantListImplement\AircraftPlantListImplement.csproj" />
</ItemGroup>

View File

@ -1,7 +1,7 @@
using AircraftPlantBusinessLogic.BusinessLogics;
using AircraftPlantContracts.BusinessLogicsContracts;
using AircraftPlantContracts.StoragesContracts;
using AircraftPlantFileImplement.Implements;
using AircraftPlantDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;