问题
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