c# - EF6 代码优先 - 具有多个表的存储过程层次结构查询
问题描述
我对 EF6 很陌生,我想用 EF 编写这个存储过程。我开始使用导航属性和“.Includes”,但这对我来说有点太复杂了。
对此的一些解释:我有分配了RoleSetId的用户。RoleSetId链接到ModuleGroup。ModuleGroup包含模块,因此用户可以根据他的RoleSetId访问这些模块。他还可以从子ModuleGroups访问模块。因此ModuleGroup可以包含Modules,但它也可以包含ModuleGroups。
这是基于RoleSetId从ModuleGroup获取Id的存储过程,然后执行递归查询以获取所有可用于 RoleSetId 的ModuleGroups ,然后返回所选ModuleGroups中包含的模块:
ALTER PROCEDURE [dbo].[GetModules] @RoleSetId int
AS
DECLARE @id INT
SET @id = (SELECT TOP 1 Id FROM ModuleGroup WHERE RoleSetId = @RoleSetId);
WITH groups AS (
SELECT mgg.ModuleGroupId, mgg.ModuleGroupSubGroupId
FROM [dbo].[ModuleGroupSubGroup] mgg
WHERE ModuleGroupId = @id
UNION ALL
SELECT mgg2.ModuleGroupId, mgg2.ModuleGroupSubGroupId
FROM [dbo].[ModuleGroupSubGroup] mgg2
JOIN groups g ON g.ModuleGroupSubGroupId = mgg2.ModuleGroupId
)
SELECT m.*
FROM Module m
INNER JOIN ModuleGroupModule mgm ON mgm.ModuleId = m.InternalId
WHERE mgm.ModuleGroupId IN (SELECT g.ModuleGroupSubGroupId FROM groups g) OR mgm.ModuleGroupId = @id
OPTION (MAXRECURSION 1000)
这是我的表格(简化):
[Table("ModuleGroup")]
public class ModuleGroup : BaseModel
{
[Key]
public int Id { get; set; }
public ICollection<ModuleGroupModule> ModuleGroupModules { get; set; }
public int RoleSetId { get; set; }
}
[Table("ModuleGroupSubGroup")]
public class ModuleGroupSubGroup : BaseModel
{
[Key]
[Column(Order = 0)]
public int ModuleGroupId { get; set; }
[Key]
[Column(Order = 1)]
[ForeignKey(nameof(ModuleGroup))]
public int ModuleGroupSubGroupId { get; set; }
public ModuleGroup ModuleGroup { get; set; }
}
[Table("ModuleGroupModule")]
public class ModuleGroupModule : BaseModel
{
[Key]
[Column(Order = 0)]
[ForeignKey(nameof(ModuleGroup))]
public int ModuleGroupId { get; set; }
[Key]
[Column(Order = 1)]
[ForeignKey(nameof(Module))]
public int ModuleId { get; set; }
public Module Module { get; set; }
public ModuleGroup ModuleGroup { get; set; }
}
[Table("Module")]
public class Module : BaseModel
{
[Key]
public int Id { get; set; }
public ICollection<ModuleGroupModule> ModuleGroupModules { get; set; }
}
更清楚地说,这里是 db 架构:
谢谢你。
解决方案
推荐阅读
- python - Pydantic:导出具有不同编码的相同类型的字段
- php - 使用 Jenkins Pipeline 将 PHP 部署到 Azure Web App 时出错
- macos - 找到了 Libfreetype.6.dylib,但架构错误
- r - tidyr::pivot_longer 合并 2 组列,每组具有不同的名称前缀
- javascript - 在 javascript azure 函数中使用 Azure 的 azcopy 工具
- netty - 是否有关于 netty 基准的详细概述以及它们在做什么?
- cloud - 即使会话终止,也可以在 Google Cloud Shell 中运行程序
- amazon-redshift - Redshift - 从 STL_QUERY_METRICS 到百分比的 CPU 时间
- javascript - 根据对象数组中的属性过滤掉非空和未定义的项目
- mongodb - 使用聚合文档查找日期可以在多个范围内的文档