用戶權(quán)限管理之用LINQ去除重復(fù)菜單項(xiàng)的操作詳解
在SQL Server數(shù)據(jù)庫(kù)開發(fā)應(yīng)用程序時(shí),用LINQ去除重復(fù)菜單項(xiàng)的操作是怎么實(shí)現(xiàn)的呢?接下來(lái)我們通過(guò)一個(gè)實(shí)例來(lái)說(shuō)明這一過(guò)程。事情是這樣的,我有三張表,用戶_角色關(guān)系表User_Role,角色_菜單關(guān)系表Role_Menu和菜單表
Menu,這三個(gè)表之間有如下關(guān)系:
User_Role=>RoleId=>RoleMenu
RoleMenu=>MenuId=>Menu
它們之間的業(yè)務(wù)關(guān)系是:當(dāng)用戶登陸后,通過(guò)UserId得到User_Role列表,將用戶所包括的角色得出,通過(guò)User_Role找到所有對(duì)應(yīng)Menu。
現(xiàn)在有個(gè)問(wèn)題,就是一個(gè)用戶可以有多少角色,一個(gè)角色有多個(gè)菜單,當(dāng)然,兩個(gè)不同的角色可以有相當(dāng)?shù)牟藛雾?xiàng),這時(shí),就出現(xiàn)一個(gè)問(wèn)題,用戶在“管理員”這個(gè)角色里有“文件”這個(gè)菜單,同時(shí)它在“新聞管理員”這個(gè)角色里也有“文件”這個(gè)菜單,這樣返回就會(huì)出現(xiàn)兩個(gè)完成相同的”文件“菜單,下面,我使用匿名類和distinct方法來(lái)解決這個(gè)問(wèn)題,代碼如下:
- class Program
- {
- static void Main(string[] args)
- {
- #region 實(shí)體列表初始化
- List<User_Role> userRole = new List<User_Role>
- {
- new User_Role("01",1),
- new User_Role("01",2),
- new User_Role("02",1),
- };
- List<Role_Menu> roleMenu = new List<Role_Menu>
- {
- new Role_Menu(2,3),
- new Role_Menu(1,1),
- new Role_Menu(1,2),
- new Role_Menu(2,1),
- new Role_Menu(2,2),
- };
- List<Menu> menu = new List<Menu>
- {
- new Menu(1,"編輯",2),
- new Menu(2,"文件",1),
- new Menu(3,"視圖",3),
- new Menu(4,"系統(tǒng)",4),
- };
- #endregion
- var linq = from data1 in userRole
- join data2 in roleMenu on data1.RoleId equals data2.RoleId
- join data3 in menu on data2.MenuId equals data3.MenuId
- where data1.UserId.Equals("01")
- select new
- {
- UserId = data1.UserId,
- MenuId = data2.MenuId,
- Menu = data3,
- };
- linq.Distinct().OrderBy(i => i.Menu.OrderNumber).ToList()
- .ForEach(i => Console.WriteLine("用戶ID:{0},菜單ID{1},菜單名:{2}"
- , i.UserId, i.MenuId, i.Menu.MenuName));
- Console.ReadKey();
- }
- }
- #region 實(shí)體對(duì)象
- class User_Role
- {
- public string UserId { get; set; }
- public int RoleId { get; set; }
- public User_Role(string userId, int roleId)
- {
- this.RoleId = roleId;
- this.UserId = userId;
- }
- }
- class Menu
- {
- public int MenuId { get; set; }
- public string MenuName { get; set; }
- public int OrderNumber { get; set; }
- public Menu(int menuId, string menuName, int orderNumber)
- {
- this.MenuId = menuId;
- this.MenuName = menuName;
- this.OrderNumber = orderNumber;
- }
- }
- class Role_Menu
- {
- public int RoleId { get; set; }
- public int MenuId { get; set; }
- public Role_Menu(int roleId, int menuId)
- {
- this.RoleId = roleId;
- this.MenuId = menuId;
- }
- }
- #endregion
這樣的結(jié)果是我希望看到的:
關(guān)于用LINQ去除重復(fù)菜單項(xiàng)的相關(guān)知識(shí)就介紹到這里了,希望本次的介紹能夠?qū)δ兴鶐椭?/p>
【編輯推薦】






