ComputerHardwareStore_YouAr.../ComputerHardwareStore/ComputerHardwareStoreDatabaseImplement/Models/Build.cs

91 lines
3.0 KiB
C#
Raw Normal View History

2024-04-30 15:57:30 +04:00

2024-04-30 18:59:45 +04:00
using ComputerHardwareStoreContracts.BindingModels;
using ComputerHardwareStoreContracts.ViewModels;
2024-04-30 15:57:30 +04:00
using ComputerHardwareStoreDataModels.Models;
2024-04-30 19:43:16 +04:00
using Microsoft.EntityFrameworkCore.Metadata.Internal;
2024-04-30 15:57:30 +04:00
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
2024-04-30 18:59:45 +04:00
using System.Runtime.InteropServices;
2024-04-30 15:57:30 +04:00
namespace ComputerHardwareStoreDatabaseImplement.Models
{
public class Build : IBuildModel
{
2024-04-30 18:59:45 +04:00
public int Id { get; set; }
2024-04-30 15:57:30 +04:00
[Required]
2024-04-30 18:59:45 +04:00
public string Name { get; set; } = string.Empty;
2024-04-30 15:57:30 +04:00
[Required]
public double Price { get; set; }
2024-04-30 19:43:16 +04:00
2024-04-30 18:59:45 +04:00
private Dictionary<int, (IComponentModel, int)>? _buildComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> BuildComponents
{
get
{
if (_buildComponents == null)
{
_buildComponents = Components
.ToDictionary(bc => bc.ComponentId, bc =>
(bc.Component as IComponentModel, bc.Count));
}
return _buildComponents;
}
}
[ForeignKey("BuildId")]
public virtual List<BuildComponent> Components { get; set; } = new();
2024-04-30 15:57:30 +04:00
[ForeignKey("BuildId")]
2024-04-30 19:43:16 +04:00
2024-04-30 18:59:45 +04:00
public virtual List<Comment> Comments { get; set; } = new();
[NotMapped]
List<ICommentModel> IBuildModel.Comments => Comments.Select(c => c as ICommentModel).ToList();
2024-04-30 19:43:16 +04:00
public virtual Vendor Vendor { get; private set; } = new();
IVendorModel IBuildModel.Vendor => Vendor as IVendorModel;
2024-04-30 18:59:45 +04:00
public static Build? Create(ComputerHardwareStoreDBContext context, BuildBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Name = model.Name,
Price = model.Price,
2024-04-30 19:43:16 +04:00
Vendor = context.Vendors.First(v => v.Id == model.Vendor.Id),
Components = context.Components
.Where(c => model.BuildComponents.ContainsKey(c.Id))
.Select(c => new BuildComponent()
{
BuildId = model.Id,
ComponentId = c.Id,
Component = c,
Count = model.BuildComponents[c.Id].Item2
}).ToList()
2024-04-30 18:59:45 +04:00
};
}
2024-04-30 20:27:11 +04:00
public void Update(BuildBindingModel model)
{
if (model == null)
{
return;
}
Name = string.IsNullOrEmpty(model.Name) ? Name : model.Name;
Price = model.Price;
}
2024-04-30 18:59:45 +04:00
public BuildViewModel GetViewModel() => new()
{
Id = Id,
Name = Name,
Price = Price,
2024-04-30 19:43:16 +04:00
Vendor = Vendor,
2024-04-30 18:59:45 +04:00
Comments = Comments.Select(c => c as ICommentModel).ToList(),
BuildComponents = BuildComponents
};
2024-04-30 15:57:30 +04:00
}
}