PIbd-21. Ivanov I.I. ThirdLaba #3

Closed
eegov wants to merge 1 commits from LabWork03 into LabWork02
15 changed files with 932 additions and 1 deletions

View File

@ -15,6 +15,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AbstractShopBusinessLogic",
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AbstractShopFileImplement", "AbstractShopFileImplement\AbstractShopFileImplement.csproj", "{3ECD0091-7E52-48C4-9529-D0BE6D6EF1DE}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AbstractShopFileImplement", "AbstractShopFileImplement\AbstractShopFileImplement.csproj", "{3ECD0091-7E52-48C4-9529-D0BE6D6EF1DE}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AbstractShopDatabaseImplement", "AbstractShopDatabaseImplement\AbstractShopDatabaseImplement.csproj", "{C76CA7A5-B719-4A01-865F-BD6FD679ECCC}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -45,6 +47,10 @@ Global
{3ECD0091-7E52-48C4-9529-D0BE6D6EF1DE}.Debug|Any CPU.Build.0 = Debug|Any CPU {3ECD0091-7E52-48C4-9529-D0BE6D6EF1DE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3ECD0091-7E52-48C4-9529-D0BE6D6EF1DE}.Release|Any CPU.ActiveCfg = Release|Any CPU {3ECD0091-7E52-48C4-9529-D0BE6D6EF1DE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3ECD0091-7E52-48C4-9529-D0BE6D6EF1DE}.Release|Any CPU.Build.0 = Release|Any CPU {3ECD0091-7E52-48C4-9529-D0BE6D6EF1DE}.Release|Any CPU.Build.0 = Release|Any CPU
{C76CA7A5-B719-4A01-865F-BD6FD679ECCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C76CA7A5-B719-4A01-865F-BD6FD679ECCC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C76CA7A5-B719-4A01-865F-BD6FD679ECCC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C76CA7A5-B719-4A01-865F-BD6FD679ECCC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -0,0 +1,25 @@
using AbstractShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace AbstractShopDatabaseImplement
{
public class AbstractShopDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=CHESHIR\SQLEXPRESS;Initial Catalog=AbstractShopDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Product> Products { set; get; }
public virtual DbSet<ProductComponent> ProductComponents { set; get; }
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="..\AbstractShopContracts\AbstractShopContracts.csproj" />
<ProjectReference Include="..\AbstractShopDataModels\AbstractShopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,84 @@
using AbstractShopContracts.BindingModels;
using AbstractShopContracts.SearchModels;
using AbstractShopContracts.StoragesContracts;
using AbstractShopContracts.ViewModels;
using AbstractShopDatabaseImplement.Models;
namespace AbstractShopDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var context = new AbstractShopDatabase();
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 AbstractShopDatabase();
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 AbstractShopDatabase();
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 AbstractShopDatabase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new AbstractShopDatabase();
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 AbstractShopDatabase();
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,40 @@
using AbstractShopContracts.BindingModels;
using AbstractShopContracts.SearchModels;
using AbstractShopContracts.StoragesContracts;
using AbstractShopContracts.ViewModels;
namespace AbstractShopDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? Delete(OrderBindingModel model)
{
throw new NotImplementedException();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
throw new NotImplementedException();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
throw new NotImplementedException();
}
public List<OrderViewModel> GetFullList()
{
throw new NotImplementedException();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
throw new NotImplementedException();
}
public OrderViewModel? Update(OrderBindingModel model)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,106 @@
using AbstractShopContracts.BindingModels;
using AbstractShopContracts.SearchModels;
using AbstractShopContracts.StoragesContracts;
using AbstractShopContracts.ViewModels;
using AbstractShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace AbstractShopDatabaseImplement.Implements
{
public class ProductStorage : IProductStorage
{
public List<ProductViewModel> GetFullList()
{
using var context = new AbstractShopDatabase();
return context.Products
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ProductViewModel> GetFilteredList(ProductSearchModel model)
{
if (string.IsNullOrEmpty(model.ProductName))
{
return new();
}
using var context = new AbstractShopDatabase();
return context.Products
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.ProductName.Contains(model.ProductName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public ProductViewModel? GetElement(ProductSearchModel model)
{
if (string.IsNullOrEmpty(model.ProductName) && !model.Id.HasValue)
{
return null;
}
using var context = new AbstractShopDatabase();
return context.Products
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ProductName) && x.ProductName == model.ProductName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ProductViewModel? Insert(ProductBindingModel model)
{
using var context = new AbstractShopDatabase();
var newProduct = Product.Create(context, model);
if (newProduct == null)
{
return null;
}
context.Products.Add(newProduct);
context.SaveChanges();
return newProduct.GetViewModel;
}
public ProductViewModel? Update(ProductBindingModel model)
{
using var context = new AbstractShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var product = context.Products.FirstOrDefault(rec => rec.Id == model.Id);
if (product == null)
{
return null;
}
product.Update(model);
context.SaveChanges();
product.UpdateComponents(context, model);
transaction.Commit();
return product.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ProductViewModel? Delete(ProductBindingModel model)
{
using var context = new AbstractShopDatabase();
var element = context.Products
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Products.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,156 @@
// <auto-generated />
using System;
using AbstractShopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace AbstractShopDatabaseImplement.Migrations
{
[DbContext(typeof(AbstractShopDatabase))]
[Migration("20230224083046_InitMigration")]
partial class InitMigration
{
/// <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("AbstractShopDatabaseImplement.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("AbstractShopDatabaseImplement.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>("ProductId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Products");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.ProductComponent", 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>("ProductId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ProductId");
b.ToTable("ProductComponents");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.ProductComponent", b =>
{
b.HasOne("AbstractShopDatabaseImplement.Models.Component", "Component")
.WithMany("ProductComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AbstractShopDatabaseImplement.Models.Product", "Product")
.WithMany("Components")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Product");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.Component", b =>
{
b.Navigation("ProductComponents");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.Product", b =>
{
b.Navigation("Components");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,114 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AbstractShopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitMigration : 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: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ProductId = 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);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ProductName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ProductComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ProductId = 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_ProductComponents", x => x.Id);
table.ForeignKey(
name: "FK_ProductComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ProductComponents_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ProductComponents_ComponentId",
table: "ProductComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_ProductComponents_ProductId",
table: "ProductComponents",
column: "ProductId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ProductComponents");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Products");
}
}
}

View File

@ -0,0 +1,153 @@
// <auto-generated />
using System;
using AbstractShopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace AbstractShopDatabaseImplement.Migrations
{
[DbContext(typeof(AbstractShopDatabase))]
partial class AbstractShopDatabaseModelSnapshot : 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("AbstractShopDatabaseImplement.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("AbstractShopDatabaseImplement.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>("ProductId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Products");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.ProductComponent", 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>("ProductId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ProductId");
b.ToTable("ProductComponents");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.ProductComponent", b =>
{
b.HasOne("AbstractShopDatabaseImplement.Models.Component", "Component")
.WithMany("ProductComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AbstractShopDatabaseImplement.Models.Product", "Product")
.WithMany("Components")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Product");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.Component", b =>
{
b.Navigation("ProductComponents");
});
modelBuilder.Entity("AbstractShopDatabaseImplement.Models.Product", b =>
{
b.Navigation("Components");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,63 @@
using AbstractShopContracts.BindingModels;
using AbstractShopContracts.ViewModels;
using AbstractShopDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AbstractShopDatabaseImplement.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<ProductComponent> ProductComponents { 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,38 @@
using AbstractShopContracts.BindingModels;
using AbstractShopContracts.ViewModels;
using AbstractShopDataModels.Enums;
using AbstractShopDataModels.Models;
namespace AbstractShopDatabaseImplement.Models
{
public class Order : IOrderModel
{
public int ProductId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; }
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; }
public int Id { get; set; }
public static Order? Create(OrderBindingModel? model)
{
return new Order();
}
public void Update(OrderBindingModel? model)
{
}
public OrderViewModel GetViewModel => new()
{
};
}
}

View File

@ -0,0 +1,96 @@
using AbstractShopContracts.BindingModels;
using AbstractShopContracts.ViewModels;
using AbstractShopDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AbstractShopDatabaseImplement.Models
{
public class Product : IProductModel
{
public int Id { get; set; }
[Required]
public string ProductName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _productComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> ProductComponents
{
get
{
if (_productComponents == null)
{
_productComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
}
return _productComponents;
}
}
[ForeignKey("ProductId")]
public virtual List<ProductComponent> Components { get; set; } = new();
public static Product Create(AbstractShopDatabase context, ProductBindingModel model)
{
return new Product()
{
Id = model.Id,
ProductName = model.ProductName,
Price = model.Price,
Components = model.ProductComponents.Select(x => new ProductComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ProductBindingModel model)
{
ProductName = model.ProductName;
Price = model.Price;
}
public ProductViewModel GetViewModel => new()
{
Id = Id,
ProductName = ProductName,
Price = Price,
ProductComponents = ProductComponents
};
public void UpdateComponents(AbstractShopDatabase context, ProductBindingModel model)
{
var productComponents = context.ProductComponents.Where(rec => rec.ProductId == model.Id).ToList();
if (productComponents != null && productComponents.Count > 0)
{ // удалили те, которых нет в модели
context.ProductComponents.RemoveRange(productComponents.Where(rec => !model.ProductComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in productComponents)
{
updateComponent.Count = model.ProductComponents[updateComponent.ComponentId].Item2;
model.ProductComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var product = context.Products.First(x => x.Id == Id);
foreach (var pc in model.ProductComponents)
{
context.ProductComponents.Add(new ProductComponent
{
Product = product,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_productComponents = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace AbstractShopDatabaseImplement.Models
{
public class ProductComponent
{
public int Id { get; set; }
[Required]
public int ProductId { get; set; }
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();
public virtual Product Product { get; set; } = new();
}
}

View File

@ -19,6 +19,10 @@
</ItemGroup> </ItemGroup>
<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="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
@ -28,6 +32,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\AbstractShopBusinessLogic\AbstractShopBusinessLogic.csproj" /> <ProjectReference Include="..\AbstractShopBusinessLogic\AbstractShopBusinessLogic.csproj" />
<ProjectReference Include="..\AbstractShopContracts\AbstractShopContracts.csproj" /> <ProjectReference Include="..\AbstractShopContracts\AbstractShopContracts.csproj" />
<ProjectReference Include="..\AbstractShopDatabaseImplement\AbstractShopDatabaseImplement.csproj" />
<ProjectReference Include="..\AbstractShopFileImplement\AbstractShopFileImplement.csproj" /> <ProjectReference Include="..\AbstractShopFileImplement\AbstractShopFileImplement.csproj" />
<ProjectReference Include="..\AbstractShopListImplement\AbstractShopListImplement.csproj" /> <ProjectReference Include="..\AbstractShopListImplement\AbstractShopListImplement.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -1,7 +1,7 @@
using AbstractShopBusinessLogic.BusinessLogics; using AbstractShopBusinessLogic.BusinessLogics;
using AbstractShopContracts.BusinessLogicsContracts; using AbstractShopContracts.BusinessLogicsContracts;
using AbstractShopContracts.StoragesContracts; using AbstractShopContracts.StoragesContracts;
using AbstractShopFileImplement.Implements; using AbstractShopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;