PIAPS_CW/DatabaseImplement/Models/Supply.cs

90 lines
2.8 KiB
C#

using Contracts.BindingModels;
using Contracts.ViewModels;
using DataModels.Enums;
using DataModels.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Models
{
public class Supply : ISupply
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
[Required]
public Guid SupplierId { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public SupplyStatus Status { get; set; } = SupplyStatus.Pending;
private Dictionary<Guid, (IProduct, int)>? _supplyProducts = null;
[NotMapped]
public Dictionary<Guid, (IProduct, int)> SupplyProducts
{
get
{
if (_supplyProducts == null)
{
_supplyProducts = Products
.ToDictionary(recPC => recPC.Id, recPC =>
(recPC.Product as IProduct, recPC.Count));
}
return _supplyProducts;
}
}
[ForeignKey("SupplyId")]
public virtual List<SupplyProduct> Products { get; set; } = new();
public virtual Supplier Supplier { get; set; }
public static Supply Create(Database context, SupplyBindingModel model)
{
return new Supply()
{
Id = model.Id,
Name = model.Name,
Price = model.Price,
Date = model.Date,
SupplierId = model.SupplierId,
Products = model.SupplyProducts.Select(x => new
SupplyProduct
{
Product = context.Products.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
Status = SupplyStatus.Pending,
};
}
public void Update(SupplyBindingModel model)
{
Status = model.Status;
}
public SupplyViewModel GetViewModel
{
get
{
var context = new Database();
return new()
{
Id = Id,
Name = Name,
Price = Price,
Products = SupplyProducts,
SupplierId = SupplierId,
Date = Date,
Status = Status,
SupplierName = Supplier.Name,
};
}
}
}
}