New to Entity Framework, trying to figure out some stuff. I have tables as listed below:
Users
---------
UserID
UserName
Roles
---------
RoleID
RoleName
UserRoles
---------
UserRoleID
UserID
RoleID
I am using a repository pattern. here’s an example of a repository (they’re all essentially the same)
public class RoleRepository : IRoleRepository
{
private AuthorizationContext context = new AuthorizationContext();
public IQueryable<Role> Roles
{
get
{
return this.context.Roles;
}
}
public bool Save(Role pRole)
{
if (pRole.RoleID == 0 || pRole.RoleID == null)
{
context.Roles.Add(pRole);
}
context.SaveChanges();
return true;
}
public bool Delete(Role pRole)
{
context.Roles.Remove(pRole);
context.SaveChanges();
return true;
}
}
Now, I want to test to see if a user (by UserName) belongs to a role (by RoleName). How can I query? I expected it to be something like this, but it doesn’t work:
public bool IsUserInRole(string username, string roleName)
{
var repo = new UserRepository();
var user = repo.Users.FirstOrDefault(u => u.NetID == username && u.UserRoles.FirstOrDefault(r => r.Role.Name == roleName));
}
How can I query to see if the user belongs to the role? I would prefer to use predicates if possible.
I would use the .Any function like this:
Here is a sample Console Application: