100 lines
3.6 KiB
C#
100 lines
3.6 KiB
C#
using ShipyardContracts.BindingModels;
|
|
using ShipyardContracts.ViewModels;
|
|
using ShipyardDatabaseImplement.Models;
|
|
using ShipyardDataModels.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 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, (IComponentModel, int)>? _shipComponents = null;
|
|
[NotMapped]
|
|
public Dictionary<int, (IComponentModel, int)> ShipComponents
|
|
{
|
|
get
|
|
{
|
|
if (_shipComponents == null)
|
|
{
|
|
_shipComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC =>
|
|
(recPC.Component as IComponentModel, recPC.Count));
|
|
}
|
|
return _shipComponents;
|
|
}
|
|
}
|
|
[ForeignKey("ShipId")]
|
|
public virtual List<ShipComponent> Components { 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,
|
|
Components = model.ShipComponents.Select(x => new
|
|
ShipComponent
|
|
{
|
|
Component = context.Components.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,
|
|
ShipComponents = ShipComponents
|
|
};
|
|
public void UpdateComponents(ShipyardDataBase context,
|
|
ShipBindingModel model)
|
|
{
|
|
var manufactureComponents = context.ShipComponents.Where(rec =>
|
|
rec.ShipId == model.Id).ToList();
|
|
if (manufactureComponents != null && ShipComponents.Count > 0)
|
|
{
|
|
context.ShipComponents.RemoveRange(manufactureComponents.Where(rec
|
|
=> !model.ShipComponents.ContainsKey(rec.ComponentId)));
|
|
context.SaveChanges();
|
|
foreach (var updateComponent in manufactureComponents)
|
|
{
|
|
updateComponent.Count =
|
|
model.ShipComponents[updateComponent.ComponentId].Item2;
|
|
model.ShipComponents.Remove(updateComponent.ComponentId);
|
|
}
|
|
context.SaveChanges();
|
|
}
|
|
var manufacture = context.Ships.First(x => x.Id == Id);
|
|
foreach (var pc in model.ShipComponents)
|
|
{
|
|
context.ShipComponents.Add(new ShipComponent
|
|
{
|
|
Ship = manufacture,
|
|
Component = context.Components.First(x => x.Id == pc.Key),
|
|
Count = pc.Value.Item2
|
|
});
|
|
context.SaveChanges();
|
|
}
|
|
_shipComponents = null;
|
|
}
|
|
}
|
|
} |