NHibernate: a query using an example of a primary key produces "WHERE (1 = 1)"

I have a customer customer

public class Customer { public virtual int ID { get; set; } public virtual string Firstname { get; set; } public virtual string Lastname { get; set; } } 

and my DAL method:

  public IList<Customer> GetCustomers(Customer example) { var customers = default(IList<Customer>); using (var sessiong = GetSession()) { customers = sessiong.CreateCriteria(typeof(Customer)) .Add(Example.Create(example)) .List<Customer>(); } return customers; } 

but the problem is that when I call my method as follows

  var exemple = new Customer() { ID = 2 }; var customers = provider.GetCustomers(exemple); 

I have a collection of all my clients in the database because NHibernate generates the following SQL query

 NHibernate: SELECT this_.CustomerId as CustomerId0_0_, this_.Firstname as Firstname0_0_, this_.Lastname as Lastname0_0_ FROM Customers this_ WHERE (1=1) 

Does NHibernate support QBE for primary key? What am I doing wrong?

PS I forgot to mention the version of NHibernate that I use. This is 2.0.1.GA.

+4
source share
2 answers

"The identifier is ignored when using the query using an example. This is because an example object with a set of identifiers in any case returns only one object." - http://forum.hibernate.org/viewtopic.php?t=927063 and http://forum.hibernate.org/viewtopic.php?p=2351666&sid=c22d2c37f8d67e268b6ffe547f57ad9e
This is for sleep mode. NHibernate has been ported from it. Therefore, I am sure that this is also a design in NHibernate. So use Get instead of QBE for id.

+11
source

What to do if you use EnableLike () in your query with the criteria criteria object to query part of the primary key + some other properties, then your query will return more than 1 record. For example: The username for the user is the primary key. The properties of the object, including the primary key, are set to the values ​​that should be requested by a similar operator. In this case, NHibernate leaves no choice but to write your own query method.

0
source

All Articles