【问题标题】:Operator '==' cannot be applied to operands of type 'ApplicationUser' and 'string'运算符“==”不能应用于“ApplicationUser”和“字符串”类型的操作数
【发布时间】:2021-06-20 19:23:20
【问题描述】:

我正在使用 asp.net 核心身份。用户 ID 在 Invite 模型中将是 FK,我正在尝试显示邀请中的所有用户

型号

    public class Invite
    {
        public int ID { get; set; }
        [ForeignKey("UserId")]    //ICollection<Invite> in User 
        [Display(Name = "Users")]
        public virtual ApplicationUser User { get; set; }
    }

=================

public class ApplicationUser : IdentityUser
    {
        public string Description { get; set; }
        [ForeignKey("GameID")] 
        public int? GameID { get; set; }
        public string GameTag { get; set; }
        public virtual ICollection<Invite> Invite { get; set; }

================
    public class Game
    {
        public int ID { get; set; }

        [Display(Name = "Game")]
        public string GameName { get; set; }
        public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }//Allow Users to get Games FKID (Foreign key ID)

    }

在邀请控制器索引中获取邀请列表并将它们放入viewbag中以获取邀请剃刀索引页面

这是错误的来源

if (i.User == tu.Id)
// GET: Invites
        public async Task<IActionResult> Index()
        {
            ViewBag.InviteList = new List<String>();
            var invite = _context.Invites;
            var theuser = _context.ApplicationUser;
            foreach (Invite i in invite)
            {
                foreach (ApplicationUser tu in theuser)
                {
                    if (i.User == tu.Id)
                    {
                        ViewBag.InviteList.Add(tu.GameID + " " +tu.GameTag);
                    }
                }
            }
            return View(await _context.Invites.ToListAsync());
        }

【问题讨论】:

  • 我假设您的Invite 模型中还缺少实际的外键属性UserId。有了这个,它将是if (i.UserId == tu.Id)

标签: asp.net-mvc asp.net-core asp.net-mvc-5 asp.net-core-identity


【解决方案1】:

因为i.UserApplicationUser 类型的对象,所以它不能与tu.Id 进行比较,tu.Id(很可能)是int 类型。

您可能想要比较两个ApplicationUser-Object 的 ID。

为此,您需要使用 i.User.Id == tu.Id,正如其他 cmets 所说的那样。

【讨论】:

    【解决方案2】:

    还有一条评论说向用户添加 .Id。它起作用了,他还说了其他我不记得的话,评论现在消失了,我不知道为什么消失了,但还是谢谢你。

    if (i.User.Id == tu.Id)
    

    【讨论】:

      【解决方案3】:

      也许你是想比较一下

      if (i.User == tu)
      {
      }
      

      【讨论】:

        猜你喜欢
        • 2016-06-30
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 2015-09-10
        • 1970-01-01
        • 1970-01-01
        • 2021-03-04
        • 2021-12-13
        相关资源
        最近更新 更多