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

115 lines
3.7 KiB
C#
Raw Normal View History

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 Name { get; set; } = string.Empty;
[Required]
public string Address { get; set; } = string.Empty;
[Required]
public DateTime OpeningDate { get; set; }
[ForeignKey("ShopId")]
public List<ShopBouquet> Bouquets { get; set; } = new();
private Dictionary<int, (IBouquetModel, int)>? _shopBouquets = null;
[NotMapped]
public Dictionary<int, (IBouquetModel, int)> ShopBouquets
{
get
{
if (_shopBouquets == null)
{
_shopBouquets = Bouquets.ToDictionary(recPC => recPC.BouquetId, recPC => (recPC.Bouquet as IBouquetModel, recPC.Count));
}
return _shopBouquets;
}
}
[Required]
public int MaxCountBouquets { get; set; }
public static Shop Create(FlowerShopDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
OpeningDate = model.OpeningDate,
Bouquets = model.ShopBouquets.Select(x => new ShopBouquet
{
Bouquet = context.Bouquets.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
MaxCountBouquets = model.MaxCountBouquets
};
}
public void Update(ShopBindingModel model)
{
Name = model.Name;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxCountBouquets = model.MaxCountBouquets;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
OpeningDate = OpeningDate,
ShopBouquets = ShopBouquets,
MaxCountBouquets = MaxCountBouquets
};
public void UpdateBouquets(FlowerShopDatabase context, ShopBindingModel model)
{
var ShopBouquets = context.ShopBouquets.Where(rec => rec.ShopId == model.Id).ToList();
if (ShopBouquets != null && this.ShopBouquets.Count > 0)
{
context.ShopBouquets.RemoveRange(ShopBouquets.Where((ShopBouquet rec) => !model.ShopBouquets.ContainsKey(rec.BouquetId)));
context.SaveChanges();
ShopBouquets = context.ShopBouquets.Where((ShopBouquet rec) => rec.ShopId == model.Id).ToList();
foreach (var updateBouquet in ShopBouquets)
{
updateBouquet.Count = model.ShopBouquets[updateBouquet.BouquetId].Item2;
model.ShopBouquets.Remove(updateBouquet.BouquetId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var elem in model.ShopBouquets)
{
context.ShopBouquets.Add(new ShopBouquet
{
Shop = shop,
Bouquet = context.Bouquets.First(x => x.Id == elem.Key),
Count = elem.Value.Item2
});
context.SaveChanges();
}
_shopBouquets = null;
}
}
}