How to make Nhibernate Case sensitive query using QueryOver?

别说谁变了你拦得住时间么 提交于 2019-12-13 04:28:34

问题


I have a simple database with users table, it have simple admin user with

UserName= "Admin"
Password="admin"

I am using NHibernate to query over this table to login form. Suppose the login form inserted UserName="ADMIN" and password="ADMIN" both in upper case.

The system should not allow login. However when I use the query like this

using (var session = NhibernateHelper.OpenSession())
{
  return new List<User>
         (session.QueryOver<User>()
                 .Where(u => u.UserName == userName)
                 .And(u => u.Password == password)
                 .Future());
}}

The system ignores the case sensitivity and selects the user. So how can I make case sensitive query?


回答1:


We can specify COLLATE directly as a part of SQL column evaluation

session
    .QueryOver<User>()
    // expecting that user name could be any case 
    // if not, we can use the same as for password below
    .Where(u => u.UserName == userName)
    // instead of this
    //.And(u => u.Password == password)
    .And(Expression.Sql(" Password = ? COLLATE Latin1_General_CS_AS"
       , password, NHibernateUtil.String));
    .Future()
    ;

The above statement will use Latin1_General_CS_AS where CS means: Case sensitive and AS means Accent sensitive

Also, there is some draft of a custom LikeExpression, which could consume the COLLATE string as a const or from setting:

  • Nhibernate QueryOver collation without hard coded column name



回答2:


Another approach, not with QueryOver, but LINQ:

session.Query<User>().Where(u => SqlMethods.Like(u.Username, "something")).ToList();



回答3:


Or, with Criteria:

session.CreateCriteria(typeof(User), "u").Add(Restrictions.Like(Projections.Property("u.Username"), "something")).List<Username>();



回答4:


Finally, QueryOver:

session.QueryOver<User>().Where(Expression.Sql("Username LIKE ?", "something", NHibernateUtil.String)).List<User>()


来源:https://stackoverflow.com/questions/23783403/how-to-make-nhibernate-case-sensitive-query-using-queryover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!