I have a pretty simple problem with a not-so-obvious solution. I have a relational mapping in my database between Users and Roles, and each user can be mapped to one or more roles. So the mapping is like so:
User < 1:n > UserRole < n:1 > Role
In my generated EF4 POCOs, User and Role each have an ICollection of the other:
public class User
{
//Bunch of other properties/methods
public virtual ICollection<Role> Roles
}
public class Role
{
//Bunch of other properties/methods
public virtual ICollection<User> Users
}
Now, I've implemented the IoC, UoW, and repository patterns illustrated in this article, which uses an ObjectSet to fetch/persist the data via repositories.
My question is, how do I implement this:
public bool UserIsInRole(int userId, int roleId)
I have tried the following:
public bool UserIsInRole(int userId, int roleId)
{
Role role = _roleRepository.Single(r => r.Id == roleId);
return _userRepository.SingleOrDefault(u => u.Roles.Contains(role)) != null;
}
But it fails with:
Unable to create a constant value of type 'Data.Models.Role'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
Plus, it's not a very elegant implementation as it's having to hit the database twice.
I was looking for something like this:
return _userRepository.SingleOrDefault(u => u.Roles.Where(r => r.Id = roleId));
But ICollection doesn't support LINQ.
How can I do this, and ideally, how can I do it with one LINQ expression and one trip to the database?
Or, am I going about this completely wrong?
Thanks in advance.
Solved: Thanks to all who posted. All gave an acceptable answer. I accepted the one that was the most elegant.