首页 > 解决方案 > EF6 代码优先 - 具有多个表的存储过程层次结构查询

问题描述

我对 EF6 很陌生,我想用 EF 编写这个存储过程。我开始使用导航属性和“.Includes”,但这对我来说有点太复杂了。

对此的一些解释:我有分配了RoleSetId的用户。RoleSetId链接ModuleGroup。ModuleGroup包含模块,因此用户可以根据他的RoleSetId访问这些模块。他还可以从子ModuleGroups访问模块。因此ModuleGroup可以包含Modules,但它也可以包含ModuleGroups

这是基于RoleSetIdModuleGroup获取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 架构:

在此处输入图像描述

谢谢你。

标签: c#sqlentity-frameworklambdaentity-framework-6

解决方案


推荐阅读