109 lines
4.0 KiB
C#
Raw Normal View History

using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SecuritySystemDatabaseImplement.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; }
[Required]
public int MaxSecuresCount { get; set; }
[ForeignKey("ShopId")]
public virtual List<ShopSecure> Secures { get; set; } = new();
private Dictionary<int, (ISecureModel, int)>? _shopSecures = null;
[NotMapped]
private int UsedSpace { get; set; }
[NotMapped]
public Dictionary<int, (ISecureModel, int)> ShopSecures
{
get
{
if (_shopSecures == null)
{
_shopSecures = Secures
.ToDictionary(
shopSecure => shopSecure.SecureId,
shopSecure => (shopSecure.Secure as ISecureModel, shopSecure.Count)
);
UsedSpace = _shopSecures.Select(x => x.Value.Item2).Sum();
}
return _shopSecures;
}
}
public static Shop Create(SecuritySystemDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
OpeningDate = model.OpeningDate,
MaxSecuresCount = model.MaxSecuresCount,
Secures = model.ShopSecures.Select(x => new ShopSecure
{
Secure = context.Secures.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel model)
{
Name = model.Name;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxSecuresCount = model.MaxSecuresCount;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
OpeningDate = OpeningDate,
MaxSecuresCount = MaxSecuresCount,
ShopSecures = ShopSecures,
UsedSpace = UsedSpace
};
public void UpdateSecures(SecuritySystemDatabase context, ShopBindingModel model)
{
var shopSecures = context.ShopSecures.Where(rec => rec.ShopId == model.Id).ToList();
if (shopSecures != null && shopSecures.Count > 0)
{
// удалили те, которых нет в модели
context.ShopSecures.RemoveRange(shopSecures.Where(rec => !model.ShopSecures.ContainsKey(rec.SecureId)));
context.SaveChanges();
shopSecures = context.ShopSecures.Where(rec => rec.ShopId == model.Id).ToList();
// обновили количество у существующих записей
foreach (var updateSecure in shopSecures)
{
updateSecure.Count = model.ShopSecures[updateSecure.SecureId].Item2;
model.ShopSecures.Remove(updateSecure.SecureId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var elem in model.ShopSecures)
{
context.ShopSecures.Add(new ShopSecure
{
Shop = shop,
Secure = context.Secures.First(x => x.Id == elem.Key),
Count = elem.Value.Item2
});
context.SaveChanges();
}
_shopSecures = null;
}
}
}