I have a Privilege
public class Privilege
{
public virtual string Name { get; set; }
public virtual ICollection<Role> Roles { get; set; } = new List<Role>();
}
I have a Role which contains a collection of Privilege
and a corresponding UserType
that the Privilege
belongs to.
public class Role
{
public virtual ICollection<Privilege> Privileges { get; set;} = new List<Privilege>();
public virtual UserType UserType { get; set;}
}
I am trying to get a List<Privilege>
from the privilege repo that only contains Privileges
which have the Role
I pass. My problem is kind of confusing because both classes have a collection of the other, and this codebase is very spaghetti like and cant be altered.
Here is my attempt, the issue is I cant actually get a List<Privilege>
but instead get this crazy IQueryable<IEnumerable<ICollection<Privilege>>>
variable back.
_privRepo.Query().Select(p => p.Roles.ToList().Where(r => r.UserType == UserType.Manager).Select(x => x.Privileges);
CodePudding user response:
assuming _privRepo
is an entityFramework DbContext, i would say something like this should do the trick :
var privileges = _privRepo.Where(p => p.Roles.Any(r => r.UserType == UserType.Manager)).ToList();
or the async version
var privileges = await _privRepo.Where(p => p.Roles.Any(r => r.UserType == UserType.Manager)).ToListAsync();
CodePudding user response:
You have to refactor your code, if it is a many to many relation then there should be another class to build the relation between them.
https://docs.microsoft.com/en-us/ef/core/modeling/relationships
though you found an workaround of your query.