100 lines
3.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
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;
public Dictionary<int, (ISecureModel, int)> ShopSecures
{
get
{
if (_shopSecures == null)
{
_shopSecures = Secures
.ToDictionary(shopSecure => shopSecure.SecureId, shopSecure => (shopSecure.Secure as ISecureModel, shopSecure.Count));
}
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
};
public void UpdateSecures(SecuritySystemDatabase context, ShopBindingModel model)
{
var shopSecures = context.ShopSecures.Where(rec => rec.SecureId == model.Id).ToList();
if (shopSecures != null && shopSecures.Count > 0)
{
// удалили те, которых нет в модели
context.ShopSecures.RemoveRange(shopSecures.Where(rec => !model.ShopSecures.ContainsKey(rec.SecureId)));
context.SaveChanges();
// обновили количество у существующих записей
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 obj in model.ShopSecures)
{
context.ShopSecures.Add(new ShopSecure
{
Shop = shop,
Secure = context.Secures.First(x => x.Id == obj.Key),
Count = obj.Value.Item2
});
context.SaveChanges();
}
_shopSecures = null;
}
}
}