Question

I have a User table related to the Company table, the relationship between them is many to one respectively. Soon the user table has CompanyID.

When a user is logged in I need to constantly check what the CompanyID him, but with User.Identity I have access only to the name.

What is the best way to get the CompanyID from logged in User?

I'm currently using Simple Membership.

Was it helpful?

Solution

Identity isn't coming from the database so it won't have all the information. The good news is that with the ID, it's easy to find your user's full record. Use UserManager<TUser>.FindByIdAsync() and feed it the result of User.Identity.GetUserId(). There's a FindByNameAsync() method too if you want.

edit: This post was originally tagged ASP.NET Identity, so I thought you were using ASP.NET Identity, which uses the UserManager class. You may not have GetUserId() in this case. Anyway, the principle is the same, even if you want to, as you've said in the comments here, access things from User.Identity. Write an extension method to IIdentity that uses your database and searches the users table for a user whose username matches the one you have. Might look something like this:

public static int GetCompanyId(this IIdentity identity)
  {
    using (var context = new ApplicationDbContext())
      {
        return context.Users.Single(u => u.UserName == identity.GetUserName()).CompanyId;
      }
  }

You can then call this by using User.Identity.GetCompanyId().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top