4

In an MVC5 application how do you get values from the AspNetUsers table for the current user?

For example: one of the default fileds is PhoneNumber. How do you get the phonenumber of the current logged in user?

I am using Identity 2...

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Steve
  • 655
  • 2
  • 9
  • 26

1 Answers1

3

You need to get the IdentityUser object (probably a descendant like ApplicationUser in your application) from Entity Framework. There are a number of ways you could do this, depending on where you are and so on. But, for example, if you wanted to do that in the controller, where you have access to the currently logged in user with the User property, you could use UserManager<TUser>.FindById() like this:

// UserManager here is an instance of UserManager<ApplicationUser>
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var number = user.PhoneNumber;
Casey
  • 3,307
  • 1
  • 26
  • 41
  • 2
    Ta for reply. Fixed it about an hour or so ago, using code similar to your approach: var manager = new UserManager(new UserStore(new ApplicationDbContext())); //Get the User object var currentUser = manager.FindById(User.Identity.GetUserId()); – Steve Apr 23 '14 at 14:06
  • You probably want to wrap that in a using statement because you want to dispose DbContexts at the end of the request. – Casey Apr 23 '14 at 14:07