首页 > 解决方案 > 如何让用户在.Net Core中只喜欢/不喜欢图片一次

问题描述

我想让用户每张图片只能给一个喜欢或不喜欢一次。我做了一个额外的模型

 public class Marking
    {
        public int IdMema { get; set; }
        public string Authorr {get;set;}
        public int Like { get; set; }
        public int Dislike { get; set; }
    }

这在 Memy 模型中

 public partial class Memy
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [HiddenInput]
        public int Id_mema { get; set; }
        public string Autor { get; set; }
        [Required]
        public string Title { get; set; }
        [HiddenInput]
        public string coverImg { get; set; }

        public string Description { get; set; }
        public string Category { get; set; }
        [HiddenInput]
        public DateTime? releaseDate { get; set; }
        public DateTime? modifyDate { get; set; }
        public int? Like { get; set; }
        public int? Dislike { get; set; }
    }

这是 MemyController 中的方法

 public async Task<IActionResult> Like(int id, Marking user)
        {

            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            var memy = db.Memy.SingleOrDefault(s => s.Id_mema == id);

            memy.Like++;
            List<Marking> ee = new List<Marking>();
            if (id != memy.Id_mema)
            {
                return NotFound();
            }
            foreach (var z in ee)
            {
                if (ModelState.IsValid && z.Authorr == currentUser.Identity.Name && z.IdMema == id && z.Like == 0)
                {

                    z.Like = 1;
                    db.Update(memy);
                    await db.SaveChangesAsync();




                }
 return RedirectToAction("Show", new { id = id });
            }



            return RedirectToAction("Show", new { id = id });
        }

我不知道为什么这不起作用。我在这里放了一个断点:

if (ModelState.IsValid && z.Authorr == currentUser.Identity.Name && z.IdMema == id && z.Like == 0) 

并且程序没有检查if,为什么?我在 MemyController 中更改了我的方法

public async Task<IActionResult> Like(int id)
        {
            var memy = db.Memy.SingleOrDefault(s => s.Id_mema == id);
            var marking = db.Marking.SingleOrDefault(s => s.IdMema == id);
            memy.Like++;
            if (id != memy.Id_mema)
            {
                return NotFound();
            }
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            if (ModelState.IsValid && marking.IdMema==id && marking.Authorr==currentUser.Identity.Name && marking.CountLike==0)
            {

                db.Update(memy);
                await db.SaveChangesAsync();

                return RedirectToAction("Show", new { id = id });
            }
            return RedirectToAction("Show", new { id = id });
        }

``
and  I add-migration and update-database ,but every time I receive answer that datebase do not contain Marking 

Thanks for help :)

标签: c#asp.net

解决方案


推荐阅读