ASP MVC5 - 身份。如何获得当前ApplicationUser [英] ASP MVC5 - Identity. How to get current ApplicationUser

查看:471
本文介绍了ASP MVC5 - 身份。如何获得当前ApplicationUser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我文章的实体在我的项目具有 ApplicationUser 命名属性作者。我怎样才能获得当前登录的完整的对象 ApplicationUser 。在创建新的文章中,我必须设置作者属性文章来电流 ApplicationUser

在老会员mechanizm这很简单,但在新的Identity mechanizm我不知道如何做到这一点。

我试图做到这一点的方式:


  • 添加using语句身份扩展名:使用Microsoft.AspNet.Identity;

  • 然后我试图让当前用户: ApplicationUser的currentUser = db.Users.FirstOrDefault(X => x.Id == User.Identity.GetUserId());

但我得到异常:


  

LINQ到实体无​​法识别方法'System.String GetUserId(System.Security.Principal.IIdentity)的方法,而这种方法不能被翻译成店前pression。
    来源=的EntityFramework



解决方案

我的错,我不应该使用LINQ查询里面的方法; P

正确code:

 字符串currentUserId = User.Identity.GetUserId();
ApplicationUser的currentUser = db.Users.FirstOrDefault(X => x.Id == currentUserId);

I have Article entity in my project which have ApplicationUser property named Author. How can I get full object of current logged ApplicationUser. While creating new article I have to set Author property in Article to current ApplicationUser.

In old Membership mechanizm it was simple but in new Identity mechanizm I don't know how to do this.

I tried to do this that way:

  • Add using statement for Identity extensions: using Microsoft.AspNet.Identity;
  • Then I try to get current user: ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == User.Identity.GetUserId());

But I get exception :

LINQ to Entities does not recognize the method 'System.String GetUserId(System.Security.Principal.IIdentity)' method, and this method cannot be translated into a store expression. Source=EntityFramework

解决方案

My mistake, I shouldn't to use method inside LINQ query ;p

Correct code:

string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

这篇关于ASP MVC5 - 身份。如何获得当前ApplicationUser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆