110 lines
2.9 KiB
C#
Raw Normal View History

2023-05-04 22:31:08 +04:00
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace ComputersShopDataBaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
[Required]
public string ShopName { get; set; } = string.Empty;
[Required]
public string ShopAddress { get; set; } = string.Empty;
[Required]
public DateTime DateOpening { get; set; }
[Required]
public int Capacity { get; set; }
private Dictionary<int, (IComputerModel, int)>? _computers = null;
[NotMapped]
public Dictionary<int, (IComputerModel, int)> Computers
{
get
{
if (_computers == null)
{
_computers = shopComputers
.ToDictionary(rec => rec.ComputerId,
rec => (rec.Computer as IComputerModel,
rec.Count));
}
return _computers;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopComputer> shopComputers { get; set; } = new();
public static Shop Create(ComputersShopDataBase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
ShopAddress = model.ShopAddress,
DateOpening = model.DateOpening,
Capacity = model.Capacity,
shopComputers = model.Computers.Select(x => new ShopComputer
{
Computer = context.Computers.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel model)
{
ShopName = model.ShopName;
ShopAddress = model.ShopAddress;
DateOpening = model.DateOpening;
Capacity = model.Capacity;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
ShopAddress = ShopAddress,
DateOpening = DateOpening,
Capacity = Capacity,
Computers = Computers
};
public void UpdateComputers(ComputersShopDataBase context, ShopBindingModel model)
{
var computers = context.ShopComputers.Where(rec => rec.ShopId == model.Id).ToList();
if (computers != null && computers.Count > 0)
{
context.ShopComputers.RemoveRange(computers.Where(rec => !model.Computers.ContainsKey(rec.ComputerId)));
context.SaveChanges();
foreach (var computer in computers)
{
computer.Count = model.Computers[computer.ComputerId].Item2;
model.Computers.Remove(computer.ComputerId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var id in model.Computers)
{
context.ShopComputers.Add(new ShopComputer
{
Shop = shop,
Computer = context.Computers.First(x => x.Id == id.Key),
Count = id.Value.Item2
});
context.SaveChanges();
}
_computers = null;
}
}
}