views:

58

answers:

1

I want to do the simplest job: Getting products which name is "Potatoes".

// solution 1 - Using Expression.Eq
return session.CreateCriteria<Product>().Add(Expression.Eq("Name", "Potatoes")).List<Product>();        

// solution 2 - Using Example
Product exampleProduct = new Product();
exampleProduct.Name = "Potatoes";
return session.CreateCriteria<Product>().Add(Example.Create(exampleProduct)).List<Product>();

Solutions 1 and 2 are supposed to be equal, Why is Solution 1 returning one object and Solution 2 returning zero objects?

EDIT

Found the solution based on Diego's answer. I didn't know how to show SQL generated by NHibernate when using Fluent. Here's a snippet for that:

r

eturn Fluently.Configure()
              .Database(
                MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(x =>
                {
                    x.TrustedConnection();
                    x.Server(@"ANDRE-PC\SQLEXPRESS");
                    x.Database("FluentHibernateTest");
                })
              ).Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>()).BuildSessionFactory();

after I saw the SQL it became clear that NHibernate was considering 0s as Diego says.

The SQL was looking like:

SELECT this_.Id as Id0_0_, this_.Name as Name0_0_, this_.Price as Price0_0_ FROM [Product] this_ WHERE (this_.Name = 'Potatoes' and this_.Price = 0); 

The Solution 2 fixed is:

// solution 2 - Using Example
Product exampleProduct = new Product();
exampleProduct.Name = "Potatoes";
return Session.CreateCriteria<Product>().Add(Example.Create(exampleProduct).ExcludeZeroes()).List<Product>();
+2  A: 

They aren't necessarily equal. Your query by example is probably including some other fields with default values (maybe something like Active = false).

You should exclude the fields you don't like to use for the filter. A good start is ExcludeZeroes().

In any case, check the resulting SQL. You can do that with the following property in your NHibernate config file:

<property name="show_sql">true</property>

...Or you can use a tool like NHProf, or your DB profiler tool, log4net output, etc.

Diego Mijelshon
Thank you very much. I updated the question to show the solution.
Ciwee