PIAPS_CW/DatabaseImplement/Models/Supplier.cs

110 lines
3.9 KiB
C#
Raw Permalink Normal View History

2024-06-22 15:10:46 +04:00
using Contracts.BindingModels;
using Contracts.ViewModels;
using DataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace DatabaseImplement.Models
{
public class Supplier : ISupplier
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public int Deals { get; set; }
private Dictionary<Guid, (IProduct, int)>? _availibleProducts = null;
[NotMapped]
public Dictionary<Guid, (IProduct, int)> AvailibleProducts
{
get
{
if (_availibleProducts == null)
{
_availibleProducts = Products
.ToDictionary(recPC => recPC.Id, recPC =>
(recPC.Product as IProduct, recPC.Count));
}
return _availibleProducts;
}
}
[ForeignKey("SupplierId")]
public virtual List<SupplierProduct> Products { get; set; } = new();
public static Supplier Create(Database context, SupplierBindingModel model)
{
return new Supplier()
{
Id = model.Id,
Name = model.Name,
Products = model.AvailibleProducts.Select(x => new
SupplierProduct
{
Product = context.Products.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(Database context, SupplierBindingModel model)
{
Name = model.Name;
Products = model.AvailibleProducts.Select(x => new
SupplierProduct
{
Product = context.Products.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList();
}
public SupplierViewModel GetViewModel
{
get
{
var context = new Database();
return new()
{
Id = Id,
Name = Name,
AvailibleProducts = AvailibleProducts
};
}
}
public void UpdateProducts(Database context, SupplierBindingModel model)
{
var supplierProducts = context.SupplierProducts.Where(rec =>
rec.Id == model.Id).ToList();
if (supplierProducts != null && supplierProducts.Count > 0)
{ // удалили те, которых нет в модели
context.SupplierProducts.RemoveRange(supplierProducts.Where(rec
=> !model.AvailibleProducts.ContainsKey(rec.ProductId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateProduct in supplierProducts)
{
updateProduct.Count = model.AvailibleProducts[updateProduct.ProductId].Item2;
model.AvailibleProducts.Remove(updateProduct.ProductId);
}
context.SaveChanges();
}
var supplier = context.Suppliers.First(x => x.Id == Id);
foreach (var pc in model.AvailibleProducts)
{
context.SupplierProducts.Add(new SupplierProduct
{
Supplier = supplier,
Product = context.Products.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_availibleProducts = null;
}
}
}