PIbd-22_Katysheva_N.E._Pizz.../Pizzeria/PizzeriaDatabaseImplement/Models/Pizza.cs

91 lines
3.4 KiB
C#
Raw Normal View History

2024-03-27 00:02:36 +04:00
using PizzeriaDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.ViewModels;
namespace PizzeriaDatabaseImplement.Models
{
public class Pizza : IPizzaModel
{
public int Id { get; set; }
2024-04-07 15:05:57 +04:00
[Required]
2024-03-27 00:02:36 +04:00
public string PizzaName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _PizzaComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> PizzaComponents
{
get
{
if (_PizzaComponents == null)
{
_PizzaComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
}
return _PizzaComponents;
}
}
[ForeignKey("PizzaId")]
public virtual List<PizzaComponent> Components { get; set; } = new();
[ForeignKey("PizzaId")]
2024-04-07 15:05:57 +04:00
2024-03-27 00:02:36 +04:00
public virtual List<Order> Orders { get; set; } = new();
public static Pizza Create(PizzeriaDatabase context, PizzaBindingModel model)
{
return new Pizza()
{
Id = model.Id,
PizzaName = model.PizzaName,
Price = model.Price,
Components = model.PizzaComponents.Select(x => new PizzaComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(PizzaBindingModel model)
{
PizzaName = model.PizzaName;
Price = model.Price;
}
public PizzaViewModel GetViewModel => new()
{
Id = Id,
PizzaName = PizzaName,
Price = Price,
PizzaComponents = PizzaComponents
};
public void UpdateComponents(PizzeriaDatabase context, PizzaBindingModel model)
{
var PizzaComponents = context.PizzaComponents.Where(rec => rec.PizzaId == model.Id).ToList();
if (PizzaComponents != null && PizzaComponents.Count > 0)
{ // удалили те, которых нет в модели
context.PizzaComponents.RemoveRange(PizzaComponents.Where(rec => !model.PizzaComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in PizzaComponents)
{
updateComponent.Count = model.PizzaComponents[updateComponent.ComponentId].Item2;
model.PizzaComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var Pizza = context.Pizzas.First(x => x.Id == Id);
foreach (var pc in model.PizzaComponents)
{
context.PizzaComponents.Add(new PizzaComponent
{
Pizza = Pizza,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_PizzaComponents = null;
}
}
}