PIbd-22_Chernyshev_Shabunov.../ComputerShopDatabaseImplement/Models/Shipment.cs

112 lines
3.0 KiB
C#

using ComputerShopContracts.BindingModels;
using ComputerShopContracts.ViewModels;
using ComputerShopDataModels.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 ComputerShopDatabaseImplement.Models
{
public class Shipment : IShipmentModel
{
public int Id { get; private set; }
[Required]
public int UserId { get; private set; }
[Required]
public string ProviderName { get; set; } = string.Empty;
[Required]
public DateTime DateShipment { get; set; } = DateTime.Now;
private Dictionary<int, IOrderModel>? _shipmentOrders = null;
[NotMapped]
public Dictionary<int, IOrderModel> ShipmentOrders
{
get
{
if (_shipmentOrders == null)
{
_shipmentOrders = Orders.ToDictionary(x => x.OrderId, x => (x.Order as IOrderModel));
}
return _shipmentOrders;
}
}
[ForeignKey("ShipmentId")]
public virtual List<ShipmentOrder> Orders { get; set; } = new();
[ForeignKey("ShipmentId")]
public virtual List<Product> Products { get; set; } = new();
public static Shipment Create(ComputerShopDatabase context, ShipmentBindingModel model)
{
return new Shipment()
{
Id = model.Id,
UserId = model.UserId,
ProviderName = model.ProviderName,
DateShipment = model.DateShipment,
Orders = model.ShipmentOrders.Select(x => new ShipmentOrder
{
Order = context.Orders.First(y => y.Id == x.Key)
}).ToList()
};
}
public void Update(ShipmentBindingModel model)
{
if (model == null)
{
return;
}
if (!string.IsNullOrEmpty(model.ProviderName))
{
ProviderName = model.ProviderName;
}
DateShipment = model.DateShipment;
}
public ShipmentViewModel GetViewModel => new()
{
Id = Id,
UserId = UserId,
ProviderName = ProviderName,
DateShipment = DateShipment,
ShipmentOrders = ShipmentOrders
};
public void UpdateOrders(ComputerShopDatabase context, ShipmentBindingModel model)
{
var shipmentOrders = context.ShipmentOrders.Where(x => x.ShipmentId == model.Id).ToList();
//удаление тех заказов, которых нет в модели
//ИСПРАВЛЕНО: удаление всех заказов
if (shipmentOrders != null && shipmentOrders.Count > 0)
{
//context.ShipmentOrders.RemoveRange(shipmentOrders.Where(x => !model.ShipmentOrders.ContainsKey(x.OrderId)));
context.ShipmentOrders.RemoveRange(shipmentOrders);
context.SaveChanges();
}
//добавление новых заказов
var currentShipment = context.Shipments.First(x => x.Id == Id);
foreach (var shipment_order in model.ShipmentOrders)
{
context.ShipmentOrders.Add(new ShipmentOrder
{
Shipment = currentShipment,
Order = context.Orders.First(x => x.Id == shipment_order.Key)
});
context.SaveChanges();
}
_shipmentOrders = null;
}
}
}