新聞中心
在SQL Server數(shù)據(jù)庫開發(fā)應(yīng)用程序時,用LINQ去除重復(fù)菜單項的操作是怎么實現(xiàn)的呢?接下來我們通過一個實例來說明這一過程。事情是這樣的,我有三張表,用戶_角色關(guān)系表User_Role,角色_菜單關(guān)系表Role_Menu和菜單表

創(chuàng)新互聯(lián)專注于臨澧網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供臨澧營銷型網(wǎng)站建設(shè),臨澧網(wǎng)站制作、臨澧網(wǎng)頁設(shè)計、臨澧網(wǎng)站官網(wǎng)定制、微信小程序開發(fā)服務(wù),打造臨澧網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供臨澧網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
Menu,這三個表之間有如下關(guān)系:
User_Role=>RoleId=>RoleMenu
RoleMenu=>MenuId=>Menu
它們之間的業(yè)務(wù)關(guān)系是:當用戶登陸后,通過UserId得到User_Role列表,將用戶所包括的角色得出,通過User_Role找到所有對應(yīng)Menu。
現(xiàn)在有個問題,就是一個用戶可以有多少角色,一個角色有多個菜單,當然,兩個不同的角色可以有相當?shù)牟藛雾?,這時,就出現(xiàn)一個問題,用戶在“管理員”這個角色里有“文件”這個菜單,同時它在“新聞管理員”這個角色里也有“文件”這個菜單,這樣返回就會出現(xiàn)兩個完成相同的”文件“菜單,下面,我使用匿名類和distinct方法來解決這個問題,代碼如下:
- class Program
- {
- static void Main(string[] args)
- {
- #region 實體列表初始化
- List
userRole = new List - {
- new User_Role("01",1),
- new User_Role("01",2),
- new User_Role("02",1),
- };
- List
roleMenu = new List - {
- 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
- {
- 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 實體對象
- 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ù)菜單項的相關(guān)知識就介紹到這里了,希望本次的介紹能夠?qū)δ兴鶐椭?/p>
名稱欄目:用戶權(quán)限管理之用LINQ去除重復(fù)菜單項的操作詳解
轉(zhuǎn)載源于:http://m.fisionsoft.com.cn/article/dhjsigj.html


咨詢
建站咨詢
