PIbd-22_Safiulova_K.N._Airc.../AircraftPlant/AircraftPlantDatabaseImplement/Models/Plane.cs

95 lines
3.6 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AircraftPlantDatabaseImplement.Models
{
public class Plane : IPlaneModel
{
public int Id { get; set; }
[Required]
public string PlaneName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _planeComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> PlaneComponents
{
get
{
if (_planeComponents == null)
{
_planeComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
}
return _planeComponents;
}
}
[ForeignKey("PlaneId")]
public virtual List<PlaneComponent> Components { get; set; } = new();
[ForeignKey("PlaneId")]
public virtual List<Order> Orders { get; set; } = new();
public static Plane Create(AircraftPlantDatabase context, PlaneBindingModel model)
{
return new Plane()
{
Id = model.Id,
PlaneName = model.PlaneName,
Price = model.Price,
Components = model.PlaneComponents.Select(x => new PlaneComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(PlaneBindingModel model)
{
PlaneName = model.PlaneName;
Price = model.Price;
}
public PlaneViewModel GetViewModel => new()
{
Id = Id,
PlaneName = PlaneName,
Price = Price,
PlaneComponents = PlaneComponents
};
public void UpdateComponents(AircraftPlantDatabase context, PlaneBindingModel model)
{
var planeComponents = context.PlaneComponents.Where(rec => rec.PlaneId == model.Id).ToList();
if (planeComponents != null && planeComponents.Count > 0)
{ // удалили те, которых нет в модели
context.PlaneComponents.RemoveRange(planeComponents.Where(rec => !model.PlaneComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in planeComponents)
{
updateComponent.Count = model.PlaneComponents[updateComponent.ComponentId].Item2;
model.PlaneComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var plane = context.Planes.First(x => x.Id == Id);
foreach (var pc in model.PlaneComponents)
{
context.PlaneComponents.Add(new PlaneComponent
{
Plane = plane,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_planeComponents = null;
}
}
}