简体   繁体   中英

Use where in row collection in Entity Framework

I have below classes :

  1. News
  2. PostPermission
  3. Role

each News Have ListOfPostPermissions(1-many) and each PostPermission have one Role (1-1).

I have List of RoleId and I want to get all News where PostPermission 's RoleId is in the List of RoleId .

I use below code but It throws error :

var roles = _currentUserService.GetCurrentUserRoles(); // List<Guid>
return NewsList.Where(row => row.Permissions.Where(role=>roles.Contains( role.RoleId)).ToList()).ToList();

I getting these errors:

Cannot implicitly convert type 'System.Collections.Generic.List' to 'bool'

Cannot convert lambda expression to delegate type 'System.Func' because some of the return types in the block are not implicitly convertible to the delegate return type

how can I do it ?

You need to use Any inside, instead of Where like this

return NewsList
    .Where(row => row.Permissions.Any(role=>roles.Contains(role.RoleId)))
    .ToList();

This is because the outer Where expects a predicate, ie expression that returns a bool . This is clearly indicated by the first exception message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM