public IActionResult Upsert(PostViewModel postView) { if (ModelState.IsValid) { if (postView.Post.ID == 0) { var u = HttpContext.Session.Get <User>(SD.CurrentUser); postView.Post.UserID = u.Id; postView.Post.DateCreate = DateTime.Now; var tags = new List <PostTag>(); foreach (var item in postView.TagSelected) { tags.Add(new PostTag() { PostId = postView.Post.ID, TagId = item }); } postView.Post.PostTags = tags; _unitOfWork.Post.Add(postView.Post); } else { var p = _db.Posts.Include(x => x.PostTags).FirstOrDefault(x => x.ID == postView.Post.ID); _db.TryUpdateManyToMany(p.PostTags, postView.TagSelected .Select(x => new PostTag { TagId = x, PostId = postView.Post.ID }), x => x.TagId); _unitOfWork.Post.Update(postView.Post); } _unitOfWork.Save(); return(RedirectToAction(nameof(Index))); } return(View(postView)); }