105 lines
3.4 KiB
C#
105 lines
3.4 KiB
C#
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;
|
|
using AutomobilePlantContracts.BindingModels;
|
|
using AutomobilePlantContracts.ViewModel;
|
|
|
|
namespace AutomobilePlantDataBaseImplements.Models
|
|
{
|
|
public class Car : ICarModel
|
|
{
|
|
public int Id { get; set; }
|
|
|
|
[Required]
|
|
public string CarName { get; set; } = string.Empty;
|
|
|
|
[Required]
|
|
public double Price { get; 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(AutoPlantDataBase context, CarBindingModel model)
|
|
{
|
|
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(AutoPlantDataBase 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;
|
|
}
|
|
}
|
|
}
|