PIbd22_Kuznetsov_A.V._Sewin.../SewingDresses/SewingDressesFileImplement/Models/Dress.cs

85 lines
3.1 KiB
C#
Raw Normal View History

2024-05-04 19:42:41 +04:00
using SewingDressesContracts.BindingModels;
using SewingDressesContracts.ViewModels;
using SewingDressesDataModels.Models;
2024-06-22 21:11:56 +04:00
using System.Runtime.Serialization;
2024-05-04 19:42:41 +04:00
using System.Xml.Linq;
namespace SewingDressesFileImplement.Models
{
2024-06-22 21:11:56 +04:00
[DataContract]
2024-05-04 19:42:41 +04:00
public class Dress : IDressModel
{
2024-06-22 21:11:56 +04:00
[DataMember]
2024-05-04 19:42:41 +04:00
public int Id { get; private set; }
2024-06-22 21:11:56 +04:00
[DataMember]
2024-05-04 19:42:41 +04:00
public string DressName { get; private set; } = string.Empty;
2024-06-22 21:11:56 +04:00
[DataMember]
2024-05-04 19:42:41 +04:00
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _dressComponents = null;
2024-06-22 21:11:56 +04:00
[DataMember]
2024-05-04 19:42:41 +04:00
public Dictionary<int, (IComponentModel, int)> DressComponents
{
get
{
if (_dressComponents == null)
{
var source = DataFileSingleton.GetInstance();
_dressComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value));
}
return _dressComponents;
}
}
public static Dress? Create(DressBindingModel model)
{
if (model == null)
{
return null;
}
return new Dress()
{
Id = model.Id,
DressName = model.DressName,
Price = model.Price,
Components = model.DressComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Dress? Create(XElement element)
{
if (element == null)
{ return null; }
return new Dress()
{
Id = Convert.ToInt32(element.Attribute("Id")?.Value),
DressName = element.Element("DressName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value, new System.Globalization.CultureInfo("en-US")),
Components = element.Element("DressComponents")!.Elements("DressComponent").ToDictionary(x =>Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(DressBindingModel model)
{
if (model == null)
{
return;
}
DressName = model.DressName;
Price = model.Price;
Components = model.DressComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_dressComponents = null;
}
public DressViewModel GetViewModel => new()
{
Id = Id,
DressName = DressName,
Price = Price,
DressComponents = DressComponents
};
public XElement GetXElement => new("Dress",
new XAttribute("Id", Id),
new XElement("DressName", DressName),
new XElement("Price", Price),
new XElement("DressComponents", Components.Select(x => new XElement("DressComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()));
}
}