PIbd-23-Nasyrov-A.G.-Flower.../FlowerShopDatabaseImplement/Flower.cs
2024-03-12 21:47:28 +04:00

98 lines
3.5 KiB
C#

using FlowerShopDataModels.Models;
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using FlowerShopDatabaseImplement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
}
}
}