PIbd-23-Salin-O.A.-IceCream.../IceCreamShop/IceCreamShopDatabaseImplement/Models/IceCream.cs
2024-03-04 19:46:39 +04:00

104 lines
3.7 KiB
C#

using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDataModels.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 IceCreamShopDatabaseImplement.Models
{
public class IceCream : IIceCreamModel
{
public int Id { get; set; }
[Required]
public string IceCreamName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _iceCreamComponents =
null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> IceCreamComponents
{
get
{
if (_iceCreamComponents == null)
{
_iceCreamComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _iceCreamComponents;
}
}
[ForeignKey("IceCreamId")]
public virtual List<IceCreamComponent> Components { get; set; } = new();
[ForeignKey("IceCreamId")]
public virtual List<Order> Orders { get; set; } = new();
public static IceCream Create(IceCreamShopDataBase context,
IceCreamBindingModel model)
{
return new IceCream()
{
Id = model.Id,
IceCreamName = model.IceCreamName,
Price = model.Price,
Components = model.IceCreamComponents.Select(x => new
IceCreamComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(IceCreamBindingModel model)
{
IceCreamName = model.IceCreamName;
Price = model.Price;
}
public IceCreamViewModel GetViewModel => new()
{
Id = Id,
IceCreamName = IceCreamName,
Price = Price,
IceCreamComponents = IceCreamComponents
};
public void UpdateComponents(IceCreamShopDataBase context,
IceCreamBindingModel model)
{
var iceCreamComponents = context.IceCreamComponents.Where(rec =>
rec.IceCreamId == model.Id).ToList();
if (iceCreamComponents != null && IceCreamComponents.Count > 0)
{
context.IceCreamComponents.RemoveRange(iceCreamComponents.Where(rec
=> !model.IceCreamComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
foreach (var updateComponent in iceCreamComponents)
{
updateComponent.Count =
model.IceCreamComponents[updateComponent.ComponentId].Item2;
model.IceCreamComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var iceCream = context.IceCreams.First(x => x.Id == Id);
foreach (var pc in model.IceCreamComponents)
{
context.IceCreamComponents.Add(new IceCreamComponent
{
IceCream = iceCream,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_iceCreamComponents = null;
}
}
}