ISEbd_21_Kuklew_M.I._Softwa.../SoftwareInstallationDatabaseImplement/Models/Package.cs
Максим Куклев 757c1ea0f0 загрузил
2024-05-12 14:45:39 +04:00

100 lines
3.6 KiB
C#

using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace SoftwareInstallationDatabaseImplement.Models
{
public class Package : IPackageModel
{
public int Id { get; set; }
[Required]
public string PackageName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _pizzaComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> PackageComponents
{
get
{
if (_pizzaComponents == null)
{
_pizzaComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _pizzaComponents;
}
}
[ForeignKey("PackageId")]
public virtual List<PackageComponent> Components { get; set; } = new();
[ForeignKey("PackageId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("PackageId")]
public virtual List<ShopPackages> ShopPackages { get; set; } = new();
public static Package
Create(SoftwareInstallationDatabase context, PackageBindingModel model)
{
return new Package()
{
Id = model.Id,
PackageName = model.PackageName,
Price = model.Price,
Components = model.PackageComponents.Select(x => new PackageComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(PackageBindingModel model)
{
PackageName = model.PackageName;
Price = model.Price;
}
public PackageViewModel GetViewModel => new()
{
Id = Id,
PackageName = PackageName,
Price = Price,
PackageComponents = PackageComponents
};
public void UpdateComponents(SoftwareInstallationDatabase context, PackageBindingModel model)
{
var pizzaComponents = context.PackageComponents.Where(rec => rec.PackageId == model.Id).ToList();
if (pizzaComponents != null && pizzaComponents.Count > 0)
{
context.PackageComponents.RemoveRange(pizzaComponents.Where(rec => !model.PackageComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
foreach (var updateComponent in pizzaComponents)
{
updateComponent.Count = model.PackageComponents[updateComponent.ComponentId].Item2;
model.PackageComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var pizza = context.Packages.First(x => x.Id == Id);
foreach (var pc in model.PackageComponents)
{
context.PackageComponents.Add(new PackageComponent
{
Package = pizza,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_pizzaComponents = null;
}
}
}