PIbd21_Makarov_DV_FlowerShop/FlowerShop/FlowerShopDatabaseImplement/Models/Shop.cs
2024-04-25 20:09:08 +04:00

105 lines
3.6 KiB
C#

using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace FlowerShopDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
[Required]
public string ShopName { get; set; } = string.Empty;
[Required]
public string Address { get; set; } = string.Empty;
[Required]
public DateTime DateOpening { get; set; }
[Required]
public int MaximumFlowers { get; set; }
private Dictionary<int, (IFlowerModel, int)>? _shopFlowers = null;
[NotMapped]
public Dictionary<int, (IFlowerModel, int)> ShopFlowers
{
get
{
if (_shopFlowers == null)
{
_shopFlowers = Flowers
.ToDictionary(x => x.FlowerId, x => (x.Flower as IFlowerModel, x.Count));
}
return _shopFlowers;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopFlower> Flowers { get; set; } = new();
public static Shop Create(FlowerShopDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
MaximumFlowers = model.MaximumFlowers,
Flowers = model.ShopFlowers.Select(x => new ShopFlower
{
Flower = context.Flowers.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel model)
{
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
MaximumFlowers = model.MaximumFlowers;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
MaximumFlowers = MaximumFlowers,
ShopFlowers = ShopFlowers
};
public void UpdateFlowers(FlowerShopDatabase context, ShopBindingModel model)
{
var shopFlowers = context.ShopFlowers.Where(rec => rec.ShopId == model.Id).ToList();
if (shopFlowers != null && shopFlowers.Count > 0)
{
context.ShopFlowers.RemoveRange(shopFlowers.Where(rec => !model.ShopFlowers.ContainsKey(rec.FlowerId)));
context.SaveChanges();
foreach (var updateFlower in shopFlowers)
{
if (model.ShopFlowers.ContainsKey(updateFlower.FlowerId))
{
updateFlower.Count = model.ShopFlowers[updateFlower.FlowerId].Item2;
model.ShopFlowers.Remove(updateFlower.FlowerId);
}
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var ic in model.ShopFlowers)
{
context.ShopFlowers.Add(new ShopFlower
{
Shop = shop,
Flower = context.Flowers.First(x => x.Id == ic.Key),
Count = ic.Value.Item2
});
context.SaveChanges();
}
_shopFlowers = null;
}
}
}