Last post Dec 19, 2017 05:33 PM by cbassett
Dec 19, 2017 04:55 PM|cbassett|LINK
How can I go about querying the AspNetUsers table (created using an out-of-box MVC 5 application, with slight modification) and retrieve the UserName with an AspNetUserId?
I have changed my AspnetUsers model so that the user logs in with a user name and not the e-mail address (which is the default for a new out of box MVC application).
My application keeps track of what each user does by the AspNetUserId and in some cases, I need to be able to go back and find out the user name of a particular entry based on the AspNetUserId. My data tables use the exact same data type as AspnetUserId
found in the AspnetUsers table that is created automatically.
Anyone know how to do this?
(I prefer to use the AspNetUserId to reference users as this allows the user to change their user name or email address and still have the information appear correctly everywhere else as all my tables that reference the User, use the AspNetUserId value that
is assigned when the user account is created.).
Dec 19, 2017 05:33 PM|cbassett|LINK
Nevermind, I found a way using Entity Framework since I'm using that to access other (non Asp.Net identity) tables in the database anyway, using the FirstOrDefault method within E-F.
here is how I did it, in case others have this same question (my database context is an instance of ApplicationDbContext called "db"):
ApplicationDbContext db = new ApplicationDbContext();
var userResult = db.AspNetUsers.FirstOrDefault(u => u.Id == TableName.AspNetUserId);
Please Note: AspNetUserId is a foreign key that links back to the AspNetUsers's Id field (which is created by default by Asp.net Identity and is used if you use the Identity 2.0 system). I just use that name so that I know what table and field it links
back to. "u.Id" references the Id field within the AspNetUsers table. It is also assumed (since the Id field in the AspNetUsers table is a primary key) that only one (or possibly no) match is returned, so I don't foresee this throwing an exceptions, unless
of course, you don't have an AspNetUsers table in your database.
However, if there is a better way to do this, please let me know.