101 lines
2.7 KiB
C#
101 lines
2.7 KiB
C#
using SewingDressesContracts.BindingModels;
|
|
using SewingDressesContracts.ViewModels;
|
|
using SewingDressesDataModels.Models;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.ComponentModel.DataAnnotations.Schema;
|
|
|
|
namespace SewingDressesDatabaseImplement.Models
|
|
{
|
|
public class Shop : IShopModel
|
|
{
|
|
public int Id { get; private set; }
|
|
[Required]
|
|
public string ShopName { get; private set; }
|
|
[Required]
|
|
public string Adress { get; private set; }
|
|
[Required]
|
|
public DateTime DateOpen { get; private set; }
|
|
[Required]
|
|
public int MaxCount { get; private set; }
|
|
private Dictionary<int, (IDressModel, int)>? _shopDresses = null;
|
|
[NotMapped]
|
|
public Dictionary<int, (IDressModel, int)>? ShopDresses
|
|
{
|
|
get
|
|
{
|
|
if ( _shopDresses == null )
|
|
{
|
|
_shopDresses = Dresses.ToDictionary(x => x.DressId, x => (x.Dress as IDressModel, x.Count));
|
|
}
|
|
return _shopDresses;
|
|
}
|
|
}
|
|
[ForeignKey("ShopId")]
|
|
public virtual List<ShopDress> Dresses { get; set; } = new();
|
|
public static Shop? Create(SewingDressesDatabase context, ShopBindingModel model)
|
|
{
|
|
if (model == null)
|
|
return null;
|
|
return new Shop()
|
|
{
|
|
Id = model.Id,
|
|
ShopName = model.ShopName,
|
|
Adress = model.Adress,
|
|
DateOpen = model.DateOpen,
|
|
MaxCount = model.MaxCount,
|
|
Dresses = model.ShopDresses.Select(x => new ShopDress
|
|
{
|
|
Dress = context.Dresses.First(y => y.Id == x.Key),
|
|
Count = x.Value.Item2
|
|
}).ToList()
|
|
};
|
|
}
|
|
public void Update(ShopBindingModel? model)
|
|
{
|
|
if (model == null )
|
|
return;
|
|
ShopName = model.ShopName;
|
|
Adress = model.Adress;
|
|
DateOpen = model.DateOpen;
|
|
MaxCount = model.MaxCount;
|
|
}
|
|
public ShopViewModel GetViewModel => new()
|
|
{
|
|
Id = Id,
|
|
ShopName = ShopName,
|
|
Adress = Adress,
|
|
DateOpen = DateOpen,
|
|
MaxCount = MaxCount,
|
|
ShopDresses = ShopDresses
|
|
};
|
|
|
|
public void UpdateDresses(SewingDressesDatabase context, ShopBindingModel model)
|
|
{
|
|
var shopDresses = context.ShopDresses.Where(rec => rec.ShopId == model.Id).ToList();
|
|
if (shopDresses != null && shopDresses.Count > 0)
|
|
{
|
|
context.ShopDresses.RemoveRange(shopDresses.Where(rec => !model.ShopDresses.ContainsKey(rec.DressId)));
|
|
context.SaveChanges();
|
|
foreach (var uDress in shopDresses)
|
|
{
|
|
uDress.Count = model.ShopDresses[uDress.DressId].Item2;
|
|
model.ShopDresses.Remove(uDress.DressId);
|
|
}
|
|
context.SaveChanges();
|
|
}
|
|
var shop = context.Shops.First(x => x.Id == Id);
|
|
foreach (var pc in model.ShopDresses)
|
|
{
|
|
context.ShopDresses.Add(new ShopDress
|
|
{
|
|
Shop = shop,
|
|
Dress = context.Dresses.First(x => x.Id == pc.Key),
|
|
Count = pc.Value.Item2
|
|
});
|
|
context.SaveChanges() ;
|
|
}
|
|
_shopDresses = null;
|
|
}
|
|
}
|
|
}
|