MVC - Cannot Query Ident Tables
I am trying to query the AspNetUsers table.
I have set the variable db
as follows
public ApplicationDbContext db = new ApplicationDbContext();
However intellisense for db
does not render any of the Identity tables, but does the others create others for the website (which are listed in IdenityModels.cs) like .......
public System.Data.Entity.DbSet<FeatureRequestMVC.Models.Feature> Features { get; set; }
How can I get the Identity tables (like AspNetUsers) listed in db
intellisense?
thank
source to share
You can use the following code to create an instance of the UserManager class,
UserManager<ApplicationUser> userManager;
userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
Once you have added all the required operators, you can call all sorts of methods to work with Identity users.
// find user by id, also available for email and username
var user = await userManager.FindByIdAsync(Id param);
// with the user object above you can delete the referenced user
await userManager.DeleteAsync(user);
// Update user
await userManager.UpdateAsync(user);
All of the above methods use the async keyword and awaits
Hope it helps.
source to share
Identity wants you to go through UserManager
for data, however there are times when you need to query identity tables. You can do something like
var sqlQuery = @"SELECT Users.UserName FROM AspNetUserClaims AS Claims
INNER JOIN AspNetUsers AS Users ON Claims.UserId = Users.Id
WHERE Claims.ClaimType = {0} AND Claims.ClaimValue = {1}";
var userName = dbContext.Database.SqlQuery<string>(sqlQuery, "MyClaimType", theClaimValue).ToList().FirstOrDefault();
This pulls in one username and sets the variable as a string. You can create a model and pass that model in SqlQuery<T>
as long as the property names match the column names or aliases in your query.
source to share