91 lines
2.9 KiB
C#
91 lines
2.9 KiB
C#
using CanteenContracts.BindingModels;
|
|
using CanteenContracts.View;
|
|
using CanteenDataModels.Models;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.ComponentModel.DataAnnotations.Schema;
|
|
|
|
namespace CanteenDatabaseImplement.Models
|
|
{
|
|
public class Product : IProductModel
|
|
{
|
|
[Required]
|
|
public string ProductName { get; private set; } = string.Empty;
|
|
[Required]
|
|
public double Cost { get; private set; }
|
|
[Required]
|
|
public int ManagerId { get; private set; }
|
|
|
|
private Dictionary<int, ICookModel>? _productCooks = null;
|
|
|
|
public int Id { get; private set; }
|
|
[NotMapped]
|
|
public Dictionary<int, ICookModel> ProductCooks
|
|
{
|
|
get
|
|
{
|
|
if (_productCooks == null)
|
|
{
|
|
_productCooks = Cooks.ToDictionary(record => record.CookId, record => record.Cook as ICookModel);
|
|
}
|
|
return _productCooks;
|
|
}
|
|
}
|
|
[ForeignKey("ProductId")]
|
|
public virtual List<ProductCook> Cooks { get; set; } = new();
|
|
|
|
[ForeignKey("ProductId")]
|
|
public virtual List<Order> Lunches { get; set; } = new();
|
|
public static Product? Create(CanteenDatabase context, ProductBindingModel model)
|
|
{
|
|
return new Product()
|
|
{
|
|
Id = model.Id,
|
|
ProductName = model.ProductName,
|
|
Cost = model.Cost,
|
|
Cooks = model.ProductCooks.Select(x => new ProductCook
|
|
{
|
|
Cook = context.Cooks.First(y => y.Id == x.Key)
|
|
}).ToList()
|
|
};
|
|
}
|
|
|
|
public void Update(ProductBindingModel model)
|
|
{
|
|
ProductName = model.ProductName;
|
|
Cost = model.Cost;
|
|
}
|
|
|
|
public ProductViewModel GetViewModel => new()
|
|
{
|
|
Id = Id,
|
|
ProductName = ProductName,
|
|
Cost = Cost,
|
|
ProductCooks = ProductCooks,
|
|
ManagerId = ManagerId
|
|
};
|
|
|
|
public void UpdateCooks(CanteenDatabase context, ProductBindingModel model)
|
|
{
|
|
var productCooks = context.ProductCooks.Where(record => record.ProductId == model.Id).ToList();
|
|
if (productCooks != null && productCooks.Count > 0)
|
|
{
|
|
context.ProductCooks.RemoveRange(productCooks.Where(record => !model.ProductCooks.ContainsKey(record.CookId)));
|
|
context.SaveChanges();
|
|
}
|
|
|
|
var product = context.Products.First(x => x.Id == Id);
|
|
foreach (var pc in model.ProductCooks)
|
|
{
|
|
context.ProductCooks.Add(new ProductCook
|
|
{
|
|
Product = product,
|
|
Cook = context.Cooks.First(x => x.Id == pc.Key),
|
|
});
|
|
context.SaveChanges();
|
|
}
|
|
|
|
_productCooks = null;
|
|
}
|
|
}
|
|
}
|