PIbd-21_Kouvshinoff_T._A._A.../AutomobilePlant/AutomobilePlantDatabaseImplement/Models/Car.cs

95 lines
3.5 KiB
C#
Raw Normal View History

2024-03-10 13:48:59 +04:00
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace AutomobilePlantDatabaseImplement.Models
{
public class Car : ICarModel
{
public int Id { get; private set; }
[Required]
public string CarName { get; private set; } = string.Empty;
[Required]
public double Price { get; private set; }
private Dictionary<int, (IComponentModel, int)>? _carComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> CarComponents
{
get
{
if (_carComponents == null)
{
_carComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
}
return _carComponents;
}
}
[ForeignKey("CarId")]
public virtual List<CarComponent> Components { get; set; } = new();
[ForeignKey("CarId")]
public virtual List<Order> Orders { get; set; } = new();
public static Car? Create(AutomobilePlantDatabase context, CarBindingModel model)
{
var components = context.Components;
return new Car()
{
Id = model.Id,
CarName = model.CarName,
Price = model.Price,
Components = model.CarComponents.Select(x => new CarComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(CarBindingModel model)
{
CarName = model.CarName;
Price = model.Price;
}
public CarViewModel GetViewModel => new()
{
Id = Id,
CarName = CarName,
Price = Price,
CarComponents = CarComponents
};
public void UpdateComponents(AutomobilePlantDatabase context, CarBindingModel model)
{
var carComponents = context.CarComponents.Where(rec => rec.CarId == model.Id).ToList();
if (carComponents != null && carComponents.Count > 0)
{ // удалили те, которых нет в модели
context.CarComponents.RemoveRange(carComponents.Where(rec => !model.CarComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in carComponents)
{
updateComponent.Count = model.CarComponents[updateComponent.ComponentId].Item2;
model.CarComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var car = context.Cars.First(x => x.Id == Id);
foreach (var pc in model.CarComponents)
{
context.CarComponents.Add(new CarComponent
{
Car = car,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_carComponents = null;
}
}
}