首页 > 解决方案 > 错误:其中一个主键值的类型与实体中定义的类型不匹配

问题描述

我不确定为什么会收到此错误。我以前可以工作,现在不行。这是内部异常错误消息:

EntitySqlException:参数类型“Edm.Int32”和“Edm.String”与此操作不兼容。在 WHERE 谓词附近,第 1 行,第 78 列。

这是它挑选出来的代码行:

Attending attending = db.Attendings.Find(userId);

这是控制器上下文中的代码:

public ActionResult Attendees(int? id)
    {
        var userId = User.Identity.GetUserId();

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Attending attending = db.Attendings.Find(userId);
        if (attending == null)
        {
            return HttpNotFound();
        }
        PopulateBeverageDropDownList(attending.BeverageId);

        return View(attending);
    }

我已经查看了 stackoverflow 和 Google,但即使我发现了类似的问题,我仍然无法弄清楚如何解决我自己的问题。

基本上我要做的是同时使用我的一个模型中的 PK 和 asp.net 身份中的 userId。这曾经可以正常工作,但我不知道弹出此错误的原因是什么。这是我的存储库的链接,用于查看完整的代码:https ://github.com/alec9876/Firepit/tree/master/Firepit

任何帮助表示赞赏!

标签: c#asp.netentity-frameworkasp.net-identity

解决方案


Find用于通过其主键获取实体。对于Attendees模型,主键是AttendeeID,与 不同的是,这是userId一个int。如果你想Attending通过它的 id 来获取,你可以将id变量传递给Find. 如果要获取Attendings用户,可以获取AttendeeID用户的,并使用Where获取Attendings,例如:

 db.Attendings.Where(x => x.AttendeeId == attendeeId)

推荐阅读