I am trying to find all users based on a specific role in my application. I currently have two roles Admin and User. When I try to return a list of users that have a role of "User" with the following linq query:
var users = context.Users
.Where(u => u.Roles.Select(r => r.RoleId).Contains("User")).ToList();
it returns 0 users. I have looked at similar questions here but many of them are now outdated. I know that RoleID for example is a hashed key and what I am searching for is plain text "User".
RoleId is not the same as the actual role name string, so that's why you're not getting any matches. The way you need to do this is:
var roleId = context.Roles.Where(m => m.Name == "User").Select(m => m.Id).SingleOrDefault();
Then:
var users = context.Users
.Where(u => u.Roles.Any(r => r.RoleId == roleId)).ToList();
Related
I have two roles (freeUser , subscribedUser) and when i try to remove a user from role (subscribed user) using
await UserManager.RemoveFromRoleAsync(subscription.UserId, RoleName.SubscribedUser);
it succesfully delete him from AspNetUserRoles table but when i check again to see if the user is subscribed using
var roles = ((ClaimsIdentity)User.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value);
var enumerable = roles as IList<string> ?? roles.ToList();
or using User.IsInRole(RoleName.SubscribedUser)
it's return ture ! and the user is still in role subscribedUser even that i checked the AspNetUserRoles table and he is delete
Delete your cookies history, check in different browser or re-start the application. Sometimes, session will validate the user even nolonger exists in database.
I add user and assign role as below code, I user ASP MVC 5 identity and EF code first.
//some Code
var result = manager.Create(insert, applicationUser.PasswordHash);
IdentityResult result2 =null;
if (result.Succeeded)
{
result2 = manager.AddToRole(insert.Id, "User");
}
//Some Code
So i need to show list of user with custom role in view like "User" role. i wrote this code :
ApplicationDbContext myDbContext = new ApplicationDbContext();
var getRoleId = myDbContext.Roles.Where(r => r.Name == "User").Select(m => m.Id).SingleOrDefault();
var fetch = myDbContext.Users.Where(u => u.Roles.Any(r => r.RoleId.ToString() == getRoleId)).ToList();
return View(fetch);
getRoleId value is "4", it is right , but fetch always count equal 0.I try more than 3 4 hours but i can not get result.Where is my wrong ? and what is the solution ?
Thank you.
UPDATE :
I found my problem in add role but i do not know how can fix that !
When adding the users to roles using the above, the users id is added to the UserId column of the UserRoles table, but there was a third column called IdentityUser_Id which was always null.
Out of curiosity I added my user id to that column as well and now the everything works. the application picked up my user role.
My follow up question to this is can I set the IdentityUser_Id automatically? using something similar to the UserManager.AddToRole() which adds the userId to both columns?
Why are you getting getRowId and not pull Users by Role Name? Try Below:
var fetch = myDbContext.Users.Where(u => u.Roles.Any(r => r.Name ==
"User")).ToList();
I have implemented ASP.Net identity with some custom properties following this article -
http://typecastexception.com/post/2014/06/22/ASPNET-Identity-20-Customizing-Users-and-Roles.aspx
Everything works well, except. I want to get users under specific role (e.g. Get me all the users under Admin role).
I tried following ways to retrieve the users -
var userRole = _roleManager.Roles.SingleOrDefault(m => m.Name == role.Name);
var usersInRole = _userManager.Users.Where(m => m.Roles.Any(r => r.RoleId == userRole.Id));
var usersInRole2 = _userService.GetUsers().Where(u => u.Roles.Any(r => r.RoleId == userRole.Id));
Where _roleManager is of type ApplicationRoleManager : RoleManager<ApplicationRole>. _userManageris of type ApplicationUserManager : UserManager<ApplicationUser, string>.
I am unable to get Roles under user in _userManager and _userService
PS : _userService is service that extends IRepository which queries DbSet<ApplicationUser>.
I can see Roles being properly mapped in table ApplicationUserRoles and I get expected result when I do _userManager.IsInRole(user.Id, "Admin");.
What could've gone wrong with this?
Rahul.
If you are using Entity Framework, it sounds like you are being caught out by lazy loading (since the roles are being added to the database but not when requested from a queryable).
Try something like the following:
_userManager.Users.Include(x => x.Roles).Where(m => m.Roles.Any(r => r.RoleId == userRole.Id));
I figured out where the issue was -
Initially the table ApplicationUserRoles had only primary key definitions, not the foreign key mapping (many to many mapping)..
I added this in OnModelCreating
modelBuilder.Entity<ApplicationUserRole>().HasKey((ApplicationUserRole r) => new { UserId = r.UserId, RoleId = r.RoleId });
//added these definitions
modelBuilder.Entity<ApplicationUser>().HasMany(p => p.Roles).WithRequired().HasForeignKey(p => p.UserId);
modelBuilder.Entity<ApplicationRole>().HasMany(p => p.Users).WithRequired().HasForeignKey(p => p.RoleId);
This completed the relationship and now I can see the Users under Roles and vice versa.
This resulted issue while updating the database, however I just had to do some changes in migration -
The object 'PK_Dbo.ApplicationUserRole' is dependent on column
'UserId'. ALTER TABLE DROP COLUMN UserId failed because one or more
objects access this column.
All I did is, I went to the migration file and moved these lines above DropColumn
DropIndex("dbo.ApplicationUserRole", new[] { "ApplicationUser_Id" });
DropIndex("dbo.ApplicationUserRole", new[] { "ApplicationRole_Id" });
DropPrimaryKey("dbo.ApplicationUserRole");
This solved the update-database exceptions as well.
Rahul
I need to get the last 10 registered users (normal users) in my application for statistics. The application has two roles: normal user and administrator user.
In my User class (Spring security), I have the dateCreated field and I can obtain the last 10 registered users in my controller with this query:
User.listOrderByDateCreated(max: 10, order: 'desc')
But I just want to get it between normal users, excluding administrator. With this query, I can obtain all normal users:
UserRole.findAllByRole(role).user
What query have I to run? Thanks.
Try this
> User.executeQuery( "from User user where user.id in (select userRole.user.id from UserRole userRole where userRole.role.id =:roleId) order by dateCreated desc", [roleId: role.id], [max: 10])
Other way is
UserRole.executeQuery( "select ur.user from UserRole ur where ur.role.id =:roleId) order by ur.user.dateCreated desc", [roleId: role.id], [max: 10])
Let me know if it works for you .. :)
Surprisingly this is a tricky one, because User doesn't have a direct handle on Role, so the GORM helpers don't help as much. Using straight Groovy list manipulation we can get what you want.
def users = User.list().findAll { it.authorities.contains role }
.sort { it.dateCreated }
.reverse()
.take(10)
//or…
def users = UserRole.findAllByRole(role).user
.sort { it.dateCreated }
.reverse()
.take(10)
However, if you have a large number of users this would be an inefficient way to get 10 of them. A better option may be to use Hibernate criteria:
def users = UserRole.createCriteria().list(max: 2) {
eq "role", role
user {
order 'dateCreated', 'desc'
}
projections { property 'user' }
}
Or if you want, you can query using HQL via executeQuery():
def users = User.executeQuery("from User where id in (select user.id from UserRole where role.id = :roleId) order by dateCreated desc", [roleId: role.id], [max: 10])
Try this:
User.findAllByRole(role,
[max: 10, sort: "dateCreated", order: "desc"])
Hi I have a linq query which I use to get data from the DB.
And I have join two tables in the query.
Here is my database structure..
I need to get Customer with primary telephone number and default shipping address.
And this is my query..
var customer=UnitOfWork.DbContext.Set<Domain.BoundedContext.ScreenPop.Entities.Customer>()
.Include(x => x.CustomerPhoneNumbers.Select(p => p.IsPrimary == true))
.Include(x => x.ShippingAddresses.Select(s => s.IsDefault == true))
.Where(c => c.CustomerId == customerQuery.CustomerId).FirstOrDefault();
But it gives me this error..
The Include path expression must refer to a navigation property defined on the type.
Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
How can I get these information by using those three tables
The includes are just a way to say what navigation properties/tables you want included. Try this
var customer=UnitOfWork.DbContext.Set<Domain.BoundedContext.ScreenPop.Entities.Customer>()
.Include(x => x.CustomerPhoneNumbers)
.Include(x => x.ShippingAddresses)
.Where(c => c.CustomerId == customerQuery.CustomerId).FirstOrDefault();
and then just get the phone number and address you want
var phonenumber = customer.CustomerPhoneNumbers.FirstOrDefault(x=>x.IsPrimary);
var address = customer.ShippingAddresses.FirstOrDefault(x=>x.IsDefault);