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

90 lines
2.9 KiB
C#
Raw Normal View History

2024-05-01 11:35:35 +04:00
using ComputerHardwareStoreContracts.BindingModels;
2024-04-30 18:59:45 +04:00
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;
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-05-29 12:38:52 +04:00
public int VendorId { get; set; }
2024-05-01 11:35:35 +04:00
[NotMapped]
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();
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-05-29 12:38:52 +04:00
VendorId = model.VendorId,
2024-04-30 19:43:16 +04:00
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-05-01 11:35:35 +04:00
public BuildViewModel GetViewModel => new()
2024-04-30 18:59:45 +04:00
{
Id = Id,
Name = Name,
Price = Price,
2024-05-29 12:38:52 +04:00
VendorId = VendorId,
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
}
}