PIbd-21_RazubaevSM_Plumbing.../PlumbingRepair/PlumbingRepairDatabaseImplement/Models/Shop.cs

110 lines
3.6 KiB
C#
Raw Normal View History


using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.ViewModels;
using PlumbingRepairDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PlumbingRepairDatabaseImplement.Models
{
public class Shop
{
public int Id { get; set; }
[Required]
public string ShopName { get; set; } = string.Empty;
[Required]
public string Address { get; set; } = string.Empty;
[Required]
public DateTime DateOpening { get; set; }
[Required]
public int maxCountWorks { get; set; }
private Dictionary<int, (IWorkModel, int)>? _shopWorks = null;
[NotMapped]
public Dictionary<int, (IWorkModel, int)> ShopWorks
{
get
{
if (_shopWorks == null)
{
_shopWorks = Works
.ToDictionary(recSW => recSW.WorkId, recSW => (recSW.Work as IWorkModel, recSW.Count));
}
return _shopWorks;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopWork> Works { get; set; } = new();
public static Shop? Create(PlumbingRepairDatabase context, ShopBindingModel? model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
maxCountWorks = model.maxCountWorks,
Address = model.Address,
ShopName = model.ShopName,
DateOpening = model.DateOpening,
Works = model.ShopWorks.Select(x => new ShopWork
{
Work = context.Works.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
return;
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
maxCountWorks = model.maxCountWorks;
}
public ShopViewModel GetViewModel => new()
{
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
maxCountWorks = maxCountWorks,
Id = Id,
ShopWorks = ShopWorks
};
public void UpdateWorks(PlumbingRepairDatabase context, ShopBindingModel model)
{
var shopWorks = context.ShopWorks.Where(rec => rec.ShopId == model.Id).ToList();
if (shopWorks != null && shopWorks.Count > 0)
{
context.ShopWorks.RemoveRange(shopWorks.Where(rec => !model.ShopWorks.ContainsKey(rec.WorkId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateWork in shopWorks)
{
updateWork.Count = model.ShopWorks[updateWork.WorkId].Item2;
model.ShopWorks.Remove(updateWork.WorkId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var pc in model.ShopWorks)
{
context.ShopWorks.Add(new ShopWork
{
Shop = shop,
Work = context.Works.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_shopWorks = null;
}
}
}