using SchoolAgainStudyContracts.BindingModel; using SchoolAgainStudyContracts.ViewModel; using SchoolAgainStudyDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolAgainStudyDataBaseImplements.Models { public class Product : IProduct { [Required] public string Title { get; set; } = string.Empty; [Required] public string Description { get; set; } = string.Empty; [Required] public DateTime DateCreate { get; set; } public int StudentId { get; set; } private Dictionary? _ProductInterests = null; [NotMapped] public Dictionary ProductInterests { get { if (_ProductInterests == null) { _ProductInterests = Interests .ToDictionary(recPC => recPC.InterestId, recPC => (recPC.Interest as IInterest)); } return _ProductInterests; } } public int Id { get; set; } [ForeignKey("ProductId")] public virtual List Interests { get; set; } = new(); [ForeignKey("ProductId")] public virtual List Lessons { get; set; } = new(); public static Product Create(SchoolDataBase context, ProductBindingModel model) { return new Product() { Id = model.Id, Title = model.Title, Description = model.Description, DateCreate = model.DateCreate, StudentId = model.StudentId, Interests = model.ProductInterests.Select(x => new ProductInterest { Interest = context.Interests.First(y => y.Id == x.Key), }).ToList() }; } public void Update(ProductBindingModel model) { Title = model.Title; Description = model.Description; DateCreate = model.DateCreate; } public ProductViewModel GetViewModel => new() { Id = Id, Title = Title, Description = Description, DateCreate = DateCreate, StudentId = StudentId, ProductInterests = ProductInterests }; public void UpdateInterests(SchoolDataBase context, ProductBindingModel model) { var productInterests = context.ProductInterests.Where(rec => rec.ProductId == model.Id).ToList(); if (productInterests != null && productInterests.Count > 0) { context.ProductInterests.RemoveRange(productInterests.Where(rec => !model.ProductInterests.ContainsKey(rec.InterestId))); context.SaveChanges(); foreach (var updateInterest in productInterests) { model.ProductInterests.Remove(updateInterest.InterestId); } context.SaveChanges(); } var product = context.Products.First(x => x.Id == Id); foreach (var pc in model.ProductInterests) { context.ProductInterests.Add(new ProductInterest { Product = product, Interest = context.Interests.First(x => x.Id == pc.Key), }); context.SaveChanges(); } _ProductInterests = null; } } }