ISEbd-21_Agliullov.D.A._Con.../ConfectioneryDatabaseImplement/Shop.cs

85 lines
2.5 KiB
C#
Raw Normal View History

using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDatabaseImplement;
using ConfectioneryDataModels;
using ConfectioneryDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Xml.Linq;
namespace ConfectioneryDatabaseImplement.Models
{
public class Shop : IShopModel
{
[Required]
public string Name { get; private set; } = string.Empty;
[Required]
public string Address { get; private set; } = string.Empty;
[Required]
public int MaxCountPastries { get; private set; }
public DateTime DateOpening { get; private set; }
private Dictionary<int, (IPastryModel, int)>? _cachedPastries = null;
[NotMapped]
public Dictionary<int, (IPastryModel, int)> Pastries
{
get
{
if (_cachedPastries == null)
{
using var context = new ConfectioneryDatabase();
_cachedPastries = ShopPastries
.ToDictionary(x => x.Id, x => (context.Pastries
.FirstOrDefault(y => y.Id == x.Id)! as IPastryModel, x.Count));
}
return _cachedPastries;
}
}
public int Id { get; private set; }
[ForeignKey("ShopId")]
public virtual List<ShopPastry> ShopPastries { get; set; } = new();
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
DateOpening = model.DateOpening,
MaxCountPastries = model.MaxCountPastries,
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Address = model.Address;
DateOpening = model.DateOpening;
// TODO update pastries
_cachedPastries = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
Pastries = Pastries,
DateOpening = DateOpening,
MaxCountPastries = MaxCountPastries,
};
}
}