2014-10-04 41 views
0

我想構建一個使用Identity 2.0角色定義用戶應該看到的菜單項的動態菜單。我對C#很新,需要一些幫助!使用Linq to Entities獲取用戶具有自我加入的角色列表

爲了達到我所做的目的,我將角色看作是菜單項,用戶可以根據分配給他們的角色看到或不看到菜單項。我有兩個級別的菜單項 - 父菜單項(如「報告」和子菜單項(如「訂單報告」,「收據報告」等)

所以我的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. 使用這些2所列出,填寫以下我的視圖模型:

    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; } 
    } 
    

基本上,我創建了一個頂級菜單和子菜單的菜單。

我的問題是,我真的不知道從哪裏開始查詢數據庫。 理想情況下,我想要一個自加入到角色表的查詢來獲得相同查詢中的父角色,但是我是C#和Linq的新手,並且不知道從哪裏開始。

任何建議將是偉大的。

回答

0

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

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

YourDBNameEntities上下文=新YourDBNameEntities();

之後,你可以加入你的附加表和你的情況自聯接:

VAR的查詢= context.AddedTable.Join(context.AddedTable,...)

var Query = from yourClassName1 in context。AddedTable

  join yourClassName2 in context.AddedTable on yourClass1.ID equals yourClass2.ID 

     where !yourClassName1.ParentRole.equals(null) 

     select new { ParentRole = yourClassName1.ParentRole }