2023-03-28 10:06:56 +04:00

112 lines
3.3 KiB
C#

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarDatabaseImplement.Models;
public class Store : IStoreModel
{
public int Id { get; private init; }
[Required]
public string StoreName { get; private set; } = string.Empty;
[Required]
public string StoreAddress { get; private set; } = string.Empty;
[Required]
public DateTime OpeningDate { get; private set; }
private Dictionary<int, (ISushiModel, int)> _sushis = null;
[NotMapped]
public Dictionary<int, (ISushiModel, int)> Sushis
{
get
{
if (_sushis == null)
{
using var context = new SushiBarDatabase();
_sushis = StoreSushi
.ToDictionary(x => x.SushiId, x => (context.Sushis
.FirstOrDefault(y => y.Id == x.SushiId)! as ISushiModel, x.Count));
}
return _sushis;
}
}
[Required]
public int maxSushi { get; private set; }
[ForeignKey("StoreId")]
public virtual List<StoreSushi> StoreSushi { get; set; } = new();
public static Store? Create(SushiBarDatabase context, StoreBindingModel? model)
{
if (model == null) return null;
return new Store
{
Id = model.Id,
StoreName = model.StoreName,
StoreAddress = model.StoreAddress,
OpeningDate = model.OpeningDate,
maxSushi = model.maxSushi,
StoreSushi = model.Sushis.Select(x => new StoreSushi()
{
Sushi = context.Sushis.FirstOrDefault(y => y.Id == x.Key)!,
Count = x.Value.Item2
}).ToList()
};
}
public void Update(StoreBindingModel? model)
{
if (model == null)
return;
StoreName = model.StoreName;
StoreAddress = model.StoreAddress;
OpeningDate = model.OpeningDate;
}
public StoreViewModel GetViewModel => new()
{
Id = Id,
StoreName = StoreName,
StoreAddress = StoreAddress,
Sushis = Sushis,
OpeningDate = OpeningDate,
maxSushi = maxSushi
};
public void UpdateSushi(SushiBarDatabase context, StoreBindingModel model)
{
var StoreSushi = context.StoreSushis
.Where(rec => rec.StoreId == model.Id)
.ToList();
if (StoreSushi.Count > 0)
{
context.StoreSushis
.RemoveRange(StoreSushi
.Where(rec => !model.Sushis
.ContainsKey(rec.SushiId)));
foreach (var updateSushi in
StoreSushi.Where(x => model.Sushis.ContainsKey(x.SushiId)))
{
updateSushi.Count = model.Sushis[updateSushi.SushiId].Item2;
model.Sushis.Remove(updateSushi.SushiId);
}
}
var shop = context.Stores.First(x => x.Id == model.Id);
shop.StoreSushi.AddRange(model.Sushis.Select(x => new StoreSushi()
{
Sushi = context.Sushis.First(y => y.Id == x.Key),
Count = x.Value.Item2,
}).Except(StoreSushi));
context.SaveChanges();
_sushis = null;
}
}