linq - 使用 Group by 时无法翻译 LINQ 表达式
问题描述
我有一个使用 EF Core DB first 方法的 Asp.net 核心 Web API。我的 SQL Server 数据库中有以下表格。
- 应用程序表 - 包含应用程序列表。
- 角色表 - 包含角色列表(用户、管理员、超级管理员等)
- 用户表 - 包含用户列表
- 用户角色表 - 包含用户和角色表之间的映射
- 功能表 - 包含功能列表(主页、用户管理等)
- RoleFeature 表 - 包含 Feature 和 Role 表之间的映射
我正在尝试获取给定 UserId 和 appId 的 RoleName 和功能列表。
以下是我到目前为止的 Linq 查询:
RoleDto role =
from a in ctx.Application.Where(x => x.ApplicationId == appId)
from r in ctx.Role.Where(x => x.ApplicationId == a.ApplicationId)
from ur in ctx.UserRole.Where(x => x.UserId == userId && x.RoleId == r.RoleId)
from rf in ctx.RoleFeature.Where(x => x.RoleId == ur.RoleId)
from f in ctx.Feature.Where(x => x.FeatureId == rf.FeatureId).Where(x => x.IsActive)
group new { r.RoleName, f.FeatureId } by ur.RoleId into g
select new RoleDto
{
Name = g.Select(x => x.RoleName).FirstOrDefault(),
FeatureIds = g.Select(x => x.FeatureId).ToList()
}.AsNoTracking()
但是,我收到一条错误消息,提示无法翻译 LINQ 表达式。
解决方案
- 您无需选择
Application
. 您可以从Role
直接选择开始 -
from r in dbCtx.Role.Where(x => x.ApplicationId == appId)
这将简化 EF 生成的最终 SQL。所以查询会更快。
- 如果 a
User
有多个Role
,那么您正在尝试获取第一个。当您选择时,您应该这样做Role
-
from r in ctx.Role.Where(x => x.ApplicationId == a.ApplicationId).Take(1)
- 最后,您可以获取 and 的列表
RoleName
,FeatureId
然后在客户端进行分组 -
var query =
from r in dbCtx.Role.Where(x => x.ApplicationId == appId).Take(1)
from ur in dbCtx.UserRole.Where(x => x.UserId == userId && x.RoleId == r.RoleId)
from rf in dbCtx.RoleFeature.Where(x => x.RoleId == ur.RoleId && x.Feature.IsActive)
select new
{
RoleName = rf.Role.RoleName,
FeatureId = rf.FeatureId
};
var roleDto = query.AsNoTracking()
.AsEnumerable()
.GroupBy(p => p.RoleName)
.Select(g => new RoleDto
{
Name = g.Key,
FeatureIds = g.Select(p => p.FeatureId).ToList()
})
.FirstOrDefault();
推荐阅读
- algorithm - 使用电晕限制优化活动座位分配
- dart - dart:如何在编译期间捕获 TypeError
- c# - 如何限制控制台输入
- mongodb - 在 mongoDB 中使用正则表达式匹配获取数据
- python - 训练时出错:tensorflow:您的输入没有数据;中断训练
- javascript - 如何在 grecaptcha.execute() 之后等到用户完成任务?reCAPTCHA v2 不可见
- css - 使用 cicerone 查找 CSS 以修改 tabPanel 的突出显示
- dataweave - 使用 DataWeave 迭代对象数组
- python - 有没有办法将嵌套的 json 数组转换为多个数组?
- c# - 带有 COM 对象的 Asp.NET CORE WEB API