PIbd-21_Anisin_R.S._CarRepa.../CarRepairShop/CarRepairShopDatabaseImplement/Models/Repair.cs
2024-03-23 14:59:30 +04:00

99 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using CarRepairShopContracts.BindingModels;
using CarRepairShopContracts.ViewModels;
using CarRepairShopDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CarRepairShopDatabaseImplement.Models
{
public class Repair : IRepairModel
{
public int Id { get; set; }
[Required]
public string RepairName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _productComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> RepairComponents
{
get
{
if (_productComponents == null)
{
_productComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
}
return _productComponents;
}
}
[ForeignKey("RepairId")]
public virtual List<RepairComponent> Components { get; set; } = new();
[ForeignKey("RepairId")]
public virtual List<Order> Orders { get; set; } = new();
public static Repair Create(CarRepairShopDatabase context, RepairBindingModel model)
{
return new Repair()
{
Id = model.Id,
RepairName = model.RepairName,
Price = model.Price,
Components = model.RepairComponents.Select(x => new RepairComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(RepairBindingModel model)
{
RepairName = model.RepairName;
Price = model.Price;
}
public RepairViewModel GetViewModel => new()
{
Id = Id,
RepairName = RepairName,
Price = Price,
RepairComponents = RepairComponents
};
public void UpdateComponents(CarRepairShopDatabase context, RepairBindingModel model)
{
var productComponents = context.RepairComponents.Where(rec => rec.RepairId == model.Id).ToList();
if (productComponents != null && productComponents.Count > 0)
{ // удалили те, которых нет в модели
context.RepairComponents.RemoveRange(productComponents.Where(rec => !model.RepairComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in productComponents)
{
updateComponent.Count = model.RepairComponents[updateComponent.ComponentId].Item2;
model.RepairComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var product = context.Repairs.First(x => x.Id == Id);
foreach (var pc in model.RepairComponents)
{
context.RepairComponents.Add(new RepairComponent
{
Repair = product,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_productComponents = null;
}
}
}