PIbd-23_Sergunov_M.A._GiftShop/GiftShop/GiftShopDatabaseImplement/Models/Gift.cs

106 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using GiftShopDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using System.Runtime.Serialization;
namespace GiftShopDatabaseImplement.Models
{
[DataContract]
public class Gift : IGiftModel
{
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string GiftName { get; set; } = string.Empty;
[Required]
[DataMember]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _giftComponents = null;
[NotMapped]
[DataMember]
public Dictionary<int, (IComponentModel, int)> GiftComponents
{
get
{
if (_giftComponents == null)
{
_giftComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _giftComponents;
}
}
[ForeignKey("GiftId")]
public virtual List<GiftComponent> Components { get; set; } = new();
[ForeignKey("GiftId")]
public virtual List<Order> Orders { get; set; } = new();
public static Gift Create(GiftShopDatabase context, GiftBindingModel model)
{
return new Gift()
{
Id = model.Id,
GiftName = model.GiftName,
Price = model.Price,
Components = model.GiftComponents.Select(x => new GiftComponent
{
Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2
}).ToList()
};
}
public void Update(GiftBindingModel model)
{
GiftName = model.GiftName;
Price = model.Price;
}
public GiftViewModel GetViewModel => new()
{
Id = Id,
GiftName = GiftName,
Price = Price,
GiftComponents = GiftComponents
};
public void UpdateComponents(GiftShopDatabase context, GiftBindingModel model)
{
var giftComponents = context.GiftComponents.Where(rec => rec.GiftId == model.Id).ToList();
if (giftComponents != null && giftComponents.Count > 0)
{ // удалили те, которых нет в модели
context.GiftComponents.RemoveRange(giftComponents.Where
(rec => !model.GiftComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in giftComponents)
{
updateComponent.Count = model.GiftComponents[updateComponent.ComponentId].Item2;
model.GiftComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var gift = context.Gifts.First(x => x.Id == Id);
foreach (var pc in model.GiftComponents)
{
context.GiftComponents.Add(new GiftComponent
{
Gift = gift,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_giftComponents = null;
}
}
}