PIbd-23_Minhasapov_R.H._Aut.../AutomobilePlant/AutomobilePlantDatabaseImplement/Models/Shop.cs

114 lines
3.7 KiB
C#
Raw Normal View History

using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.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;
namespace AutomobilePlantDatabaseImplement.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; }
[ForeignKey("ShopId")]
public List<ShopCar> Cars { get; set; } = new();
private Dictionary<int, (ICarModel, int)>? _shopCars = null;
[NotMapped]
public Dictionary<int, (ICarModel, int)> ShopCars
{
get
{
if (_shopCars == null)
{
_shopCars = Cars.ToDictionary(recPC => recPC.CarId, recPC => (recPC.Car as ICarModel, recPC.Count));
}
return _shopCars;
}
}
[Required]
public int MaxCountCars { get; set; }
public static Shop Create(AutomobilePlantDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
OpeningDate = model.OpeningDate,
Cars = model.ShopCars.Select(x => new ShopCar
{
Car = context.Cars.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
MaxCountCars = model.MaxCountCars
};
}
public void Update(ShopBindingModel model)
{
Name = model.Name;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxCountCars = model.MaxCountCars;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
OpeningDate = OpeningDate,
ShopCars = ShopCars,
MaxCountCars = MaxCountCars
};
public void UpdateCars(AutomobilePlantDatabase context, ShopBindingModel model)
{
var ShopCars = context.ShopCars.Where(rec => rec.ShopId == model.Id).ToList();
if (ShopCars != null && ShopCars.Count > 0)
{
// удалили те, которых нет в модели
context.ShopCars.RemoveRange(ShopCars.Where(rec => !model.ShopCars.ContainsKey(rec.CarId)));
context.SaveChanges();
ShopCars = context.ShopCars.Where(rec => rec.ShopId == model.Id).ToList();
// обновили количество у существующих записей
foreach (var updateCar in ShopCars)
{
updateCar.Count = model.ShopCars[updateCar.CarId].Item2;
model.ShopCars.Remove(updateCar.CarId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var elem in model.ShopCars)
{
context.ShopCars.Add(new ShopCar
{
Shop = shop,
Car = context.Cars.First(x => x.Id == elem.Key),
Count = elem.Value.Item2
});
context.SaveChanges();
}
_shopCars = null;
}
}
}