sqlserver 用户权限管理,LINQ去除它的重复菜单项

这样的结果是我希望看到的:

using System;
using System.Collections;
using System.Collections.Generic;
using Castle.Facilities.NHibernateIntegration;
using Castle.Services.Transaction;
using Cuyahoga.Core.Util;
using NHibernate;
using NHibernate.Criterion;

  <class name=”NHibernateTest.Model.Role,NHibernateTest.Model” table=”T_Role”>

Menu,这三个表之间有如下关系: User_Role=RoleId=RoleMenu
RoleMenu=MenuId=Menu 它们之间的业务关系是:
当用户登陆后,通过UserId得到User_Role列表,将用户所包括的角色得出
通过User_Role找到所有对应Menu
现在有个问题,就是一个用户可以有多少角色,一个角色有多个菜单,当然,两个不同的角色可以有相当的菜单项,这时,就出现一个问题,用户在“管理员”这个角色里有“文件”这个菜单,同时它在“新闻管理员”这个角色里也有“文件”这个菜单,这样返回就会出现两个完成相同的”文件“菜单,下面,我使用匿名类和distinct方法来解决这个问题,代码如下:
复制代码 代码如下: class Program { static
void Main(string[] args) { #region 实体列表初始化 ListUser_Role
userRole = new ListUser_Role { new User_Role(“01”,1), new
User_Role(“01”,2), new User_Role(“02″,1), }; ListRole_Menu roleMenu =
new ListRole_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), }; ListMenu
menu = new ListMenu { new Menu(1,”编辑”,2), new Menu(2,”文件”,1), new
Menu(3,”视图”,3), new Menu(4,”系统”,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

        #region IUserDao Members

table=”T_User”>

        public IList FindUsersByUsername(string searchString)
        {
            if (searchString.Length > 0)
            {
                ISession session = this._sessionManager.OpenSession();
                string hql = “from User u where u.UserName like ? order by u.UserName “;
                return session.Find(hql, searchString + “%”, NHibernateUtil.String);
            }
            else
            {
                return this._commonDao.GetAll(typeof(User), “UserName”);
            }
        }
        //根据条件分页
        public IList<User> FindUsers(string username, int? roleId, bool? isActive, int? siteId, int pageSize, int pageNumber, out int totalCount)
        {
            ISession session = this._sessionManager.OpenSession();
            ICriteria userCriteria = session.CreateCriteria(typeof(User));
            ICriteria countCriteria = session.CreateCriteria(typeof(User), “userCount”);

               
User user =
session.Load(typeof(User), 5) as User;

        /// <summary>
        /// Default constructor;
        /// </summary>
        /// <param name=”sessionManager”></param>
        public UserDao(ISessionManager sessionManager, ICommonDao commonDao)
        {
            this._sessionManager = sessionManager;
            this._commonDao = commonDao;
        }

        {

 

    [Serializable]

using Cuyahoga.Core.Domain;

―――――――――――――――――――――――――

        public User GetUserByUsernameAndPassword(string username, string password)
        {
            ISession session = this._sessionManager.OpenSession();

 

            string hql = “select s from Section s join s.SectionPermissions sp, Role r “+
                “where r.PermissionLevel = :permission and r.Id = sp.Role.Id and sp.ViewAllowed = 1”;
            IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
            q.SetInt32(“permission”, permission);
            return q.List<Section>();
        }
        public IList<Role> GetRolesByRightName(string rightName)
        {
            string hql = “select r from Role r join r.Rights right where right.Name = :rightName”;
            IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
            q.SetString(“rightName”, rightName);
            return q.List<Role>();
        }

 

            if (!String.IsNullOrEmpty(username))
            {
                //username相似:从开始匹配
                userCriteria.Add(Expression.InsensitiveLike(“UserName”, username, MatchMode.Start));
                countCriteria.Add(Expression.InsensitiveLike(“UserName”, username, MatchMode.Start));
            }
            if (roleId.HasValue)
            {
                userCriteria.CreateCriteria(“Roles”, “r1”).Add(Expression.Eq(“r1.Id”, roleId));
                countCriteria.CreateCriteria(“Roles”, “r1”).Add(Expression.Eq(“r1.Id”, roleId));
            }
            if (isActive.HasValue)
            {
                userCriteria.Add(Expression.Eq(“IsActive”, isActive));
                countCriteria.Add(Expression.Eq(“IsActive”, isActive));
            }
            if (siteId.HasValue && ! roleId.HasValue)
            {
                
                DetachedCriteria roleIdsForSite = DetachedCriteria.For(typeof (Role))
                    .SetProjection(Projections.Property(“Id”))
                    .CreateCriteria(“Sites”, “site”)//Sites 别名site
                    .Add(Expression.Eq(“site.Id”, siteId.Value));
                DetachedCriteria userIdsForRoles = DetachedCriteria.For(typeof(User))
                    .SetProjection(Projections.Distinct(Projections.Property(“Id”)))
                    .CreateCriteria(“Roles”)
                    .Add(Subqueries.PropertyIn(“Id”, roleIdsForSite));
                userCriteria.Add(Subqueries.PropertyIn(“Id”, userIdsForRoles));
                countCriteria.Add(Subqueries.PropertyIn(“Id”, userIdsForRoles));
                //里面的属性方法有待进一步查阅资料
            }
            userCriteria.SetFirstResult((pageNumber – 1) * pageSize);
            userCriteria.SetMaxResults(pageSize);
            countCriteria.SetProjection(Projections.RowCount());
            totalCount = (int) countCriteria.UniqueResult();
            return userCriteria.List<User>();
        }

 

        [Transaction(TransactionMode.Requires)]
        public void SaveOrUpdateUser(User user)
        {
            ISession session = this._sessionManager.OpenSession();
            session.SaveOrUpdate(user);
        }

public partial class Many_To_Many : System.Web.UI.Page

        public IList<Role> GetAllRolesBySite(Site site)
        {
            ISession session = this._sessionManager.OpenSession();
            ICriteria crit = session.CreateCriteria(typeof (Role))
                .AddOrder(Order.Asc(“Name”))
                .CreateCriteria(“Sites”)
                .Add(Expression.Eq(“Id”, site.Id));
            return crit.List<Role>();
        }

 {

澳门金沙vip 1澳门金沙vip 2代码

using NHibernate.Cfg;

        public IList<Section> GetViewableSectionsByUser(User user)
        {

               
role.Users.Add(user);

        #endregion
    }
}

            }

namespace Cuyahoga.Core.DataAccess
{
    /// <summary>
    /// Provides data access for user-related components.
    /// </summary>
    [Transactional]
    public class UserDao : IUserDao
    {
        private ISessionManager _sessionManager;
        private ICommonDao _commonDao;

 

            //:userId参数User和Role进行了关联映射所以可以用u.Rolse来获取Role的相关数据
            string hql = “select s from User u join u.Roles as r, Section s join s.SectionPermissions sp ” +
                        “where u.Id = :userId and r.Id = sp.Role.Id and sp.ViewAllowed = 1”;
            IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
            q.SetInt32(“userId”, user.Id);
            return q.List<Section>();
        }

            get { return
_username; }

            ICriteria crit = session.CreateCriteria(typeof(User));
            crit.Add(Expression.Eq(“UserName”, username));
            crit.Add(Expression.Eq(“Password”, password));
            IList results = crit.List();
            if (results.Count == 1)
            {
                return (User)results[0];
            }
            else if (results.Count > 1)
            {
                throw new Exception(String.Format(“Multiple users found with the give username and password. Something is pretty wrong here”));
            }
            else
            {
                return null;
            }
        }

            finally

        [Transaction(TransactionMode.Requires)]
        public void DeleteUser(User user)
        {
            ISession session = this._sessionManager.OpenSession();
            session.Delete(user);
        }

        private IList _澳门金沙vip,roles;

             public IList<Section> GetViewableSectionsByAccessLevel(AccessLevel accessLevel)
        {
            int permission = (int)accessLevel;

            {

 

            }

            set { _rolename = value; }

               
trans.Commit();

            set { _userpassword = value; }

    Id

            {

RoleName

            ITransaction trans =
session.BeginTransaction();

            }

            }

            _userid
= 0;

namespace NHibernateTest

User表id

//更新了与UserId=6关联的Role的RoleName名字

     
<key column=”RoleId”/>

 

               
throw new Exception(“失败!”);

        {

            ISession session =
sessions.OpenSession();

               
Role role = new Role();

            ISession session =
sessions.OpenSession();

        private int
_userid;

 {

                
//更新了与UserId=6关联的Role的RoleName名字

        {

 

            {

            get { return
_roles; }

<?xml version=”1.0″ encoding=”utf-8″
?>

            ISession session =
sessions.OpenSession();

        //添加了User,Role 以及User-Role的关系

               
trans.Commit();

            }

               
throw new Exception(“失败!”);

            catch

            set { _username = value; }

     *  在删除User时一般不会要求删除Role,而是删除之间的关系

            get { return
_rolename; }

 

            {

<!–指定关联类(Role)在连接表(T_User_Role)中的外键列名RoleId –>

 

 

protected void
TestDeleteUserWithSetRole_Click(object
sender, EventArgs e)

            try

}

               
session.Close();

           
config.AddAssembly(“NHibernateTest.Model”);

            }

               
session.Update(user);

    {

            ISessionFactory sessions =
config.BuildSessionFactory();

  /* DELETE
FROM T_User_Role WHERE UserId = @p0′, N’@p0 int’, @p0 =
10

            get { return
_userpassword; }

     */

            }

User类映射文件User.hbm.xml:

            finally

            }

  protected void Page_Load(object sender, EventArgs e)

        public virtual string RoleName

        public virtual string UserPassword

Int主键自增

using System.Web.UI.WebControls;

  
UserName

}

           
config.AddAssembly(“NHibernateTest.Model”);

            Configuration config = new Configuration();

  }

               
User user =
session.Load(typeof(User), 6) as User;

            try

               
role.RoleName = “秘书”;

               
trans.Rollback();

protected void
TestAddUserAndRole_Click(object
sender, EventArgs e)

    [Serializable]

实现代码如下:

using System.Web;

            catch

        }

 

protected void
TestUpdateUserWithRole_Click(object
sender, EventArgs e)

T_User表

}

               
session.Update(user);

using System.Collections;

{

            finally

        public virtual IList Users

using System.Collections.Generic;

        }

        {

    }