簡體   English   中英

使用Linq to Entities獲取用戶通過自我聯接擁有的角色列表

[英]Using Linq to Entities to get a list of roles that a user has with a self join

我正在嘗試構建一個使用Identity 2.0角色的動態菜單,以定義用戶應看到的菜單項。 我是C#的新手,需要一些幫助!

出於我正在做的目的,我考慮一個角色作為菜單項,用戶可以根據分配給他們的角色看到或不看到。 我有兩個菜單項級別-父菜單項(例如“報告”)和子菜單項(例如“訂單報告”,“收貨報告”等)。

所以我的ApplicationRole類看起來像這樣:

public string Description { get; set; }
public string MenuTitle {get;set;}
public string MenuIcon { get; set; }
public string ControllerName { get; set; }
public string ActionName { get; set; }

public virtual ApplicationRole ParentRole { get; set; }

我將僅針對用戶存儲角色,而ParentRole不為null。 我想知道為登錄用戶檢索此角色列表並呈現菜單。

因此,邏輯將類似於:

  1. 獲取用戶已為其分配的所有菜單項(角色)的列表。
  2. 使用此列表,使用ParentRole可以獲取父角色的獨特列表(菜單的頂層)。
  3. 使用這兩個列表,在下面填充我的視圖模型:

     public class NavigationViewModel { public int MenuId { get; set; } public string MenuName { get; set; } public string ControllerName { get; set; } public string ActionName { get; set; } public string MenuIcon { get; set; } public IEnumerable<NavigationViewModel> ChildMenuItems { get; set; } } 

基本上,我正在創建一個具有頂級菜單和子菜單的菜單。

我的問題是,就查詢數據庫而言,我真的不知道從哪里開始。 理想情況下,我希望使用一個自我聯接到Role表的查詢,以在同一查詢中獲得Parent Role,但是我是C#和Linq的新手,並且不知道從哪里開始。

任何建議都很好。

我的建議是將ADO.NET Entity Data Model添加到項目中,然后從數據庫中添加要查詢的表。 然后一個.edmx文件與表和它們之間的關系創建,您可以在代碼中訪問它們(一DbContext與你的數據庫名稱,如創建YouDBNameEntities )。

現在您已連接到數據庫,創建一個新的上下文:

YourDBNameEntities上下文=新的YourDBNameEntities();

之后,您可以加入已添加的表,並進行自我連接:

var Query = context.AddedTable.Join(context.AddedTable,...)

要么

var Query =來自context.AddedTable中的yourClassName1

  join yourClassName2 in context.AddedTable on yourClass1.ID equals yourClass2.ID where !yourClassName1.ParentRole.equals(null) select new { ParentRole = yourClassName1.ParentRole } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM