public async Task <double> GetArticleLikes(int id) { var db = new LikesDb(); double likesCount = db.Likes.Where(x => x.ArticleId == id).Count(); return(likesCount); }
public async Task <ActionResult> AddLike(int id) { var db = new ArticlesDb(); var likeDb = new LikesDb(); var article = db.Articles.Find(id); var userId = HttpContext.User.Identity.GetUserId(); var like = likeDb.Likes.Where(x => x.UserId == userId && x.ArticleId == article.Id).FirstOrDefault(); //user already liked this so remove like if (like != null) { if (article != null) { likeDb.Likes.Remove(like); await likeDb.SaveChangesAsync(); article.Likes = await GetArticleLikes(id); await db.SaveChangesAsync(); } } else { if (article != null) { like = new Like(); like.ArticleId = article.Id; like.UserId = userId; likeDb.Likes.Add(like); await likeDb.SaveChangesAsync(); article.Likes = await GetArticleLikes(id); await db.SaveChangesAsync(); } } return(PartialView("~/Views/Articles/Partials/LikesCount.cshtml", article)); }