2024-03-24 13:58:43 +04:00

90 lines
3.3 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 ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace ShipyardDataBaseImplement.Models
{
public class Ship : IShipModel
{
public int Id { get; set; }
[Required]
public string ShipName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IDetailModel, int)>? _shipDetails = null;
[NotMapped]
public Dictionary<int, (IDetailModel, int)> ShipDetails
{
get
{
if (_shipDetails == null)
{
_shipDetails = Details.ToDictionary(recPC => recPC.DetailId, recPC =>
(recPC.Detail as IDetailModel, recPC.Count));
}
return _shipDetails;
}
}
[ForeignKey("ShipId")]
public virtual List<ShipDetail> Details { get; set; } = new();
[ForeignKey("ShipId")]
public virtual List<Order> Orders { get; set; } = new();
public static Ship Create(ShipyardDataBase context, ShipBindingModel model)
{
return new Ship()
{
Id = model.Id,
ShipName = model.ShipName,
Price = model.Price,
Details = model.ShipDetails.Select(x => new ShipDetail
{
Detail = context.Details.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShipBindingModel model)
{
ShipName = model.ShipName;
Price = model.Price;
}
public ShipViewModel GetViewModel => new()
{
Id = Id,
ShipName = ShipName,
Price = Price,
ShipDetails = ShipDetails
};
public void UpdateComponents(ShipyardDataBase context,
ShipBindingModel model)
{
var shipDetails = context.ShipDetails.Where(rec => rec.ShipId == model.Id).ToList();
if (shipDetails != null && shipDetails.Count > 0)
{ // удалили те, которых нет в модели
context.ShipDetails.RemoveRange(shipDetails.Where(rec => !model.ShipDetails.ContainsKey(rec.DetailId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateDetail in shipDetails)
{
updateDetail.Count = model.ShipDetails[updateDetail.DetailId].Item2;
model.ShipDetails.Remove(updateDetail.DetailId);
}
context.SaveChanges();
}
var ship = context.Ships.First(x => x.Id == Id);
foreach (var pc in model.ShipDetails)
{
context.ShipDetails.Add(new ShipDetail
{
Ship = ship,
Detail = context.Details.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_shipDetails = null;
}
}
}