PIbd-23_Polevoy_S.V._Flower.../FlowerShop/FlowerShopDatabaseImplement/Models/Bouquet.cs

101 lines
3.4 KiB
C#

using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FlowerShopDatabaseImplement.Models
{
public class Bouquet : IBouquetModel
{
public int Id { get; private set; }
[Required]
public string BouquetName { get; private set; } = string.Empty;
[Required]
public double Price { get; private set; }
private Dictionary<int, (IComponentModel, int)>? _bouquetComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> BouquetComponents
{
get
{
if (_bouquetComponents == null)
{
_bouquetComponents = Components.ToDictionary(record => record.ComponentId, record => (record.Component as IComponentModel, record.Count));
}
return _bouquetComponents;
}
}
[ForeignKey("BouquetId")]
public virtual List<BouquetComponent> Components { get; set; } = new();
[ForeignKey("BouquetId")]
public virtual List<Order> Orders { get; set; } = new();
public static Bouquet? Create(FlowerShopDatabase context, BouquetBindingModel model)
{
return new Bouquet()
{
Id = model.Id,
BouquetName = model.BouquetName,
Price = model.Price,
Components = model.BouquetComponents.Select(x => new BouquetComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(BouquetBindingModel model)
{
BouquetName = model.BouquetName;
Price = model.Price;
}
public BouquetViewModel GetViewModel => new()
{
Id = Id,
BouquetName = BouquetName,
Price = Price,
BouquetComponents = BouquetComponents
};
public void UpdateComponents(FlowerShopDatabase context, BouquetBindingModel model)
{
var bouquetComponents = context.BouquetComponents.Where(record => record.BouquetId == model.Id).ToList();
if (bouquetComponents != null && bouquetComponents.Count > 0)
{
context.BouquetComponents.RemoveRange(bouquetComponents.Where(record => !model.BouquetComponents.ContainsKey(record.ComponentId)));
context.SaveChanges();
foreach (var updateComponent in bouquetComponents)
{
updateComponent.Count = model.BouquetComponents[updateComponent.ComponentId].Item2;
model.BouquetComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var bouquet = context.Bouquets.First(x => x.Id == Id);
foreach (var pc in model.BouquetComponents)
{
context.BouquetComponents.Add(new BouquetComponent
{
Bouquet = bouquet,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_bouquetComponents = null;
}
}
}