I'm using entity framework 2.2.
I have a very basic setup: User, UserRole, Role.
Ideally, I would like to do operations like these: User.Roles.Where(...). But I can't.
I have to pollute the application logic with data structure details, so I have to do something like this: User.UserRoles.Where(x => x.Role...).
Is there any way to accomplish this?
I've tried to define an expression for finding the users with a specific role:
public static Expression<Func<User, bool>> HasRole(string role)
{
return user => user.UserRoles.Any(x => x.Role.Name == role);
}
And call it like this:
var admins = await _context.Users
.Where(User.HasRole("Admin"))
.ToListAsync();
So that I don't need to know about the UserRole table.
I am aware that there's an open issue on github, but I was thinking what workarounds we could use for now?
I've seen another approach on the internet:
public IEnumerable<Role> Roles => this.userRoles.Select(x => x.Role);
It would've been perfect if it could be automatically translated into Expression somehow, but I need to Include UserRoles before I can use user.Roles, which basically, doesn't solve my problem.