PIbd22_NikiforovaMV_Automob.../AutomobilePlantFileImplement/Models/Car.cs

111 lines
3.4 KiB
C#
Raw Normal View History

2024-04-17 10:17:17 +04:00
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
2024-06-22 22:32:20 +04:00
using System.Runtime.Serialization;
2024-04-17 10:17:17 +04:00
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models
{
2024-06-22 22:32:20 +04:00
[DataContract]
public class Car : ICarModel
2024-04-17 10:17:17 +04:00
{
2024-06-22 22:32:20 +04:00
[DataMember]
public string CarName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
[DataMember]
public int Id { get; private set; }
2024-04-17 10:17:17 +04:00
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _carComponents = null;
2024-06-22 22:32:20 +04:00
[DataMember]
public Dictionary<int, (IComponentModel, int)> CarComponents
2024-04-17 10:17:17 +04:00
{
get
{
if (_carComponents == null)
{
var source = DataFileSingleton.GetInstance();
_carComponents = Components.ToDictionary(
x => x.Key,
y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)
);
}
return _carComponents;
}
}
public static Car? Create(CarBindingModel? model)
{
if (model == null)
{
return null;
}
return new Car()
{
Id = model.Id,
CarName = model.CarName,
Price = model.Price,
Components = model.CarComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Car? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Car()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
CarName = element.Element("CarName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components = element.Element("CarComponents")!.Elements("CarComponent").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(CarBindingModel? model)
{
if (model == null)
{
return;
}
CarName = model.CarName;
Price = model.Price;
Components = model.CarComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_carComponents = null;
}
public CarViewModel GetViewModel => new()
{
Id = Id,
CarName = CarName,
Price = Price,
CarComponents = CarComponents
};
public XElement GetXElement => new(
"Car",
new XAttribute("Id", Id),
new XElement("CarName", CarName),
new XElement("Price", Price.ToString()),
new XElement("CarComponents", Components.Select(x =>
new XElement("CarComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}