Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate : Query by example on primary key produces "WHERE (1=1)"

Tags:

nhibernate

I have an entity 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 is :

    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 like this

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

I have a collection of all my customers 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)

NHibernate supports QBE on primary key ? What am I doing wrong ?

P.S. I've forgotten to mention the version of NHibernate that I'm using. It's 2.0.1.GA.

like image 880
Petar Petrov Avatar asked Dec 22 '22 13:12

Petar Petrov


1 Answers

"The ID is ignored when using query by example. This is done because an example object with the id set would return only one object anyways." - http://forum.hibernate.org/viewtopic.php?t=927063 and http://forum.hibernate.org/viewtopic.php?p=2351666&sid=c22d2c37f8d67e268b6ffe547f57ad9e
This is for Hibernate. NHibernate was ported from it. So I'm sure that this is by design in NHibernate too. So use Get instead of QBE on id.

like image 89
zihotki Avatar answered Feb 22 '23 23:02

zihotki