2010-01-14 27 views
0

我想做最简单的工作:获得名为“土豆”的产品。为什么即使最简单的NHibernate示例条件不起作用?

// 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>(); 

溶液1和2应该是相等的,为什么是解决方案1返回一个对象和溶液2返回零个对象?

编辑

发现基于迭戈的回答解决方案。我不知道如何在使用Fluent时显示由NHibernate生成的SQL。下面是一个片段:

[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(); 

我看到的NHibernate正在考虑0迭戈说,很明显的SQL后。

的SQL一直在寻找这样的:

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); 

固定解决方案2:

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

回答

2

他们不一定相等。您通过示例查询可能包含一些其他字段的默认值(可能类似Active = false)。

您应该排除不想用于过滤器的字段。一个好的开始是ExcludeZeroes()

无论如何,请检查生成的SQL。你可以做到这一点与下列财产在你的NHibernate的配置文件:

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

...或者你可以使用一个工具,如NHProf,或者您的数据库Profiler工具,log4net的输出等

+0

非常感谢你许多。我更新了问题以显示解决方案。 –

相关问题