using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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? _planeComponents = null;
[NotMapped]
public Dictionary 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 Components { get; set; } = new();
///
/// Связь с заказами
///
[ForeignKey("PlaneId")]
public virtual List 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;
}
}
}