SUBD_Aleikin/Restaurant/RestaurantDatabaseImplement/Models/Product.cs

114 lines
3.9 KiB
C#
Raw Normal View History

using RestaurantContracts.BindingModels;
using RestaurantContracts.ViewModels;
using RestaurantDataModels.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 RestaurantDatabaseImplement.Models
{
public class Product : IProductModel
{
[Required]
public string Type { get; private set; } = string.Empty;
[Required]
public int Price { get; private set; }
[Required]
public int Count { get; private 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;
}
}
public int Id { get; private set; }
[ForeignKey("ProductId")]
public virtual List<ProductComponent> Components { get; private set; } = new();
[ForeignKey("ProductId")]
public virtual List<OrderProduct> OrderProducts { get; private set; } = new();
public static Product? Create(RestaurantDatabase context, ProductBindingModel? model)
{
if (model == null)
{
return null;
}
return new Product()
{
Id = model.Id,
Type = model.Type,
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)
{
Type = model.Type;
Price = model.Price;
Count = model.Count;
}
public ProductViewModel GetViewModel => new()
{
Id = Id,
Type = Type,
Price = Price,
Count = Count,
ProductComponents = ProductComponents
};
public void UpdateComponents(RestaurantDatabase 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;
}
}
}