【问题标题】:Use where in row collection in Entity Framework在实体框架的行集合中使用 where
【发布时间】:2015-12-21 11:49:39
【问题描述】:

我有以下课程:

  1. 新闻
  2. 发布权限
  3. 角色

每个新闻都有 ListOfPostPermissions(1-many),每个 PostPermission 有一个角色 (1-1)。

我有RoleId 的列表,我想获取所有News,其中PostPermissionRoleIdRoleId 的列表中。

我使用下面的代码,但它会抛出错误:

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

我收到这些错误:

无法将类型“System.Collections.Generic.List”隐式转换为 '布尔'

无法将 lambda 表达式转换为委托类型“System.Func” 因为块中的某些返回类型不是隐式的 可转换为委托返回类型

我该怎么做?

【问题讨论】:

  • 错误信息是什么?

标签: c# entity-framework linq entity-framework-6


【解决方案1】:

你需要在里面使用Any,而不是像这样的Where

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

这是因为外部Where 需要一个谓词,即返回bool 的表达式。第一条异常消息清楚地表明了这一点。

【讨论】:

  • 您的代码返回此错误:'bool' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?)
  • 我删除了First ToList 这样的return NewsList.Where(row =&gt;row.Permissions.Any(role=&gt;roles.Contains(role.RoleId))).ToList(); 现在没有Error 了吧?
  • @PsarTak 抱歉,我没有仔细查看整个查询,因为将Where 替换为Any 是必不可少的部分。更正了答案。
猜你喜欢
  • 1970-01-01
  • 2015-08-19
  • 2018-12-06
  • 1970-01-01
  • 2011-10-20
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多