Hoàng Nguyễn
Hoàng Nguyễn

Reputation: 1170

Filter list by condition as nested element inside an element

I want to return a list of users that filters their specific roles. A user can have several roles, but the user list always exclude users who have one of roles as 'PRIMARY'. I included two conditions in where() method but the list only filters the first condition.

  IList<Account> users = _context.Account.AsNoTracking()
    .Include(a => a.Profile)
    .Include(a => a.AccountRole)
    .ThenInclude(r => r.Role)
    .Where(a => (a.Organization == "My Company") && 
          (a.AccountRole.Any(r => r.Role.Name != "PRIMARY")))
    .ToList();

Upvotes: 0

Views: 44

Answers (4)

Feras Al Sous
Feras Al Sous

Reputation: 1083

You should edit the a.AccountRole.Any(r => r.Role.Name != "PRIMARY") to !a.AccountRole.Any(r => r.Role.Name != "PRIMARY").

Upvotes: 0

Snippy Valson
Snippy Valson

Reputation: 361

I think the problem is with the second condition the where clause. Could you try changing it as :

IList<Account> users = _context.Account.AsNoTracking()
    .Include(a => a.Profile)
    .Include(a => a.AccountRole)
    .ThenInclude(r => r.Role)
    .Where(a => (a.Organization == "My Company") && 
          (! a.AccountRole.Any(r => r.Role.Name == "PRIMARY")))
    .ToList();

This may work as the second condition will only work if there is no "PRIMARY" role in the AccountRole.

Upvotes: 1

Antoine V
Antoine V

Reputation: 7204

exclude users who have one of roles as 'PRIMARY'

So, following the logic: it must be.

IList<Account> users = _context.Account.AsNoTracking()
    .Include(a => a.Profile)
    .Include(a => a.AccountRole)
    .ThenInclude(r => r.Role)
    .Where(a => !a.AccountRole.Any(r => r.Role.Name == "PRIMARY") // can't contain a role PRIMARY 
        && a.Organization == "My Company")
    .ToList();

Upvotes: 1

Rafalon
Rafalon

Reputation: 4515

a.AccountRole.Any(r => r.Role.Name != "PRIMARY")

Written like this, it means

all the users which have at least one role not being "PRIMARY"

What you want instead is:

!a.AccountRole.Any(r => r.Role.Name == "PRIMARY")

all the users which do not have any role being "PRIMARY"

Upvotes: 3

Related Questions