PIbd21_Makarov_DV_FlowerShop/FlowerShop/FlowerShopDatabaseImplement/Models/Flower.cs

92 lines
3.4 KiB
C#

using FlowerShopDataModels.Models;
using FlowerShopContracts.ViewModels;
using FlowerShopContracts.BindingModels;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace FlowerShopDatabaseImplement.Models
{
public class Flower : IFlowerModel
{
public int Id { get; set; }
[Required]
public string FlowerName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _FlowerComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> FlowerComponents
{
get
{
if (_FlowerComponents == null)
{
_FlowerComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _FlowerComponents;
}
}
[ForeignKey("FlowerId")]
public virtual List<FlowerComponent> Components { get; set; } = new();
[ForeignKey("FlowerId")]
public virtual List<Order> Orders { get; set; } = new();
public static Flower Create(FlowerShopDatabase context, FlowerBindingModel model)
{
return new Flower()
{
Id = model.Id,
FlowerName = model.FlowerName,
Price = model.Price,
Components = model.FlowerComponents.Select(x => new FlowerComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(FlowerBindingModel model)
{
FlowerName = model.FlowerName;
Price = model.Price;
}
public FlowerViewModel GetViewModel => new()
{
Id = Id,
FlowerName = FlowerName,
Price = Price,
FlowerComponents = FlowerComponents
};
public void UpdateComponents(FlowerShopDatabase context, FlowerBindingModel model)
{
var FlowerComponents = context.FlowerComponents.Where(rec => rec.FlowerId == model.Id).ToList();
if (FlowerComponents != null && FlowerComponents.Count > 0)
{
context.FlowerComponents.RemoveRange(FlowerComponents.Where(rec
=> !model.FlowerComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
foreach (var updateComponent in FlowerComponents)
{
updateComponent.Count = model.FlowerComponents[updateComponent.ComponentId].Item2;
model.FlowerComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var Flower = context.Flowers.First(x => x.Id == Id);
foreach (var pc in model.FlowerComponents)
{
context.FlowerComponents.Add(new FlowerComponent
{
Flower = Flower,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_FlowerComponents = null;
}
}
}