Fluent NHibernate Where Clause
Asked Answered
P

3

23

I have to write a query in Fluent NHibernate for

Select * from Users where UserName = 'Abcd' AND Password = '123456'

How to create above query with session.CreateCriteria

Patterman answered 12/7, 2011 at 4:10 Comment(0)
P
52

Fluent NHibernate is a alternative Mapping framework to the default HBM files (Hibernate Mapping)

NHibernate itself offers different Querying API's like

  • HQL - Hibernate Querying Language
  • Criteria
  • Query - (LINQ Equivalent)
  • QueryOver - (strongly typed Criteria)
  • SQL

For Criteria your query would be something along the lines of:

var users = session.CreateCriteria<Users>()
                   .Add(Restrictions.Eq("UserName", "Abcd"))
                   .Add(Restrictions.Eq("Password", "123456"))
                   .List<Users>();

Query:

var users = from u in session.Query<Users>()
            where u.UserName == "Abcd"
            && u.Password == "123456"
            select u;

or

var users = session.Query<Users>()
                   .Where(x => x.UserName == "Abcd" && u.Password == "123456");

QueryOver:

var users = session.QueryOver<Users>()
                   .Where(x => x.UserName == "Abcd")
                   .And(u.Password == "123456")
                   .List();
Peptic answered 12/7, 2011 at 4:46 Comment(4)
thanks for the great reply. Can i return a User as a type in the above queries ?Patterman
@Patterman - A single user? Instead of a Collection? Sure. You can look at 'SingleOrDefault()' on the Query/QueryOver, instead of 'List()'. I'm not sure which method you call on the Criteria to do a single result. Don't have Visual Studio handy.Peptic
Can this be done in fluent mapping too? greatful if you could give an example of the sameSemiannual
@Semiannual - Fluent Mapping is just an in memory xml mapping. The mapping doesn't have any influence on your ability to run queries. Unless you get the mapping wrong.Peptic
S
0

Query Over

var users = session.QueryOver<Users>()
                   .Where(x => x.UserName == "Abcd" && x.Password == "123456")
                   .List();
Steadman answered 23/7, 2015 at 11:34 Comment(0)
T
0

If you are using IQuery:

User user = new User();
user.username="Abcd";
user.password="123456";

IQuery q = session.CreateQuery("from foo in class Foo where
user.username=:username and user.password=:password");
q.SetProperties(user);
var users= q.List<User>(); 
Tantra answered 29/2, 2020 at 1:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.