using BlogDataModels.Model; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations.Schema; using BlogContracts.BindingModel; namespace BlogDatabaseImplement.Model { public class News : INews { public string Title { get; set; } = string.Empty; public string Text { get; set; } = string.Empty; public int UserId { get; set; } public int Id { get; set; } public virtual User User { get; set; } private Dictionary? _NewsTag = null; [NotMapped] public Dictionary NewsTag { get { if (_NewsTag == null) { _NewsTag = Tags.ToDictionary(recPC => recPC.TagId, recPC => (recPC.Tag as ITag, recPC.Count)); } return _NewsTag; } } [ForeignKey("NewsId")] public virtual List Tags { get; set; } = new(); [ForeignKey("NewsId")] public virtual List Comments { get; set; } = new(); public static News Create(BlogDatabase context, NewsBindingModel model) { var news = new News() { Id = model.Id, Title = model.Title, Text = model.Text, UserId = model.UserId }; news.Tags = model.NewsTag.Select(x => new NewsTag { Tag = context.Tags.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList(); return news; } public void Update(NewsBindingModel model) { Title = model.Title; Text = model.Text; UserId = model.UserId; } public BlogContracts.ViewModels.NewsViewModel GetViewModel => new() { Id = Id, Title = Title, Text = Text, UserId = UserId }; public void UpdateTags(BlogDatabase context, NewsBindingModel model) { var NewsTags = context.NewsTags.Where(rec => rec.NewsId == model.Id).ToList(); if (NewsTags != null && NewsTags.Count > 0) { // удалили те, которых нет в модели context.NewsTags.RemoveRange(NewsTags.Where(rec => !model.NewsTag.ContainsKey(rec.TagId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateTag in NewsTags) { updateTag.Count = model.NewsTag[updateTag.TagId].Item2; model.NewsTag.Remove(updateTag.TagId); } context.SaveChanges(); } var News = context.News.First(x => x.Id == Id); foreach (var pc in model.NewsTag) { context.NewsTags.Add(new NewsTag { News = News, Tag = context.Tags.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _NewsTag = null; } } }