Nhibernate 的聚合函数
今天遇到的问题:
Hql="select max(SNInfo.Ln) from SNInfo",设置MaxResult(1),执行这条查询时,
返回的是SNInfo对象,其中LN是519,query的返回结果集也不是1。
改为
IQuery q = _coreRepository.ActiveSession.CreateQuery("select max(s.Ln) from SNInfo as s" );
q.UniqueResult();
发现,不能用类名修饰字段,必须用别名。
查找NHibernate源代码:
if( (dialect is Dialect.MsSql2000Dialect) )
{
Assert.AreEqual( 1, s.Find("from s in class Simple where lower( s.Name + ' foo' ) = 'simple 1 foo'").Count );
}
{
Assert.AreEqual( 1, s.Find("from s in class Simple where lower( s.Name + ' foo' ) = 'simple 1 foo'").Count );
}
if( (dialect is Dialect.SybaseDialect) )
{
Assert.AreEqual( 1, s.Find("from s in class Simple where lower( concat(s.Name, ' foo') ) = 'simple 1 foo'").Count );
}
疑问:{
Assert.AreEqual( 1, s.Find("from s in class Simple where lower( concat(s.Name, ' foo') ) = 'simple 1 foo'").Count );
}
"in class" 和 as的功能相似?
某些函数,如lower在不同的数据库中语法不同,在NHibernate中用发也不同,这样还怎么跨数据库?
enumerable = s.Enumerable(
"select max(foo.Component.ImportantDates.elements) from foo in class Foo group by foo.id"
);
IEnumerator enumerator = enumerable.GetEnumerator();
Assert.IsTrue( enumerator.MoveNext() );
Assert.IsTrue( enumerator.Current is DateTime );
可以同过IEnumerator 获取数据,且效率比find()高"select max(foo.Component.ImportantDates.elements) from foo in class Foo group by foo.id"
);
IEnumerator enumerator = enumerable.GetEnumerator();
Assert.IsTrue( enumerator.MoveNext() );
Assert.IsTrue( enumerator.Current is DateTime );
Entities returned as results are initialized on demand. The first SQL query returns
identifiers only. So Enumerator()is usually a less efficient way to retrieve
object than Find()
调用例子:
enumerable = s.Enumerable( "select count(foo) from foo in class Foo where foo.id=?",
foo.Key, NHibernateUtil.String );
<param name="query">The query string</param>foo.Key, NHibernateUtil.String );
第二个参数:<param name="value">A value to be written to a "?" placeholder in the query string</param>代替?占位符的值
第三个:<param name="type">The hibernate type of the value</param>
后面两个参数会组合成QueryParameters定义如下:
public QueryParameters( IType[ ] positionalParameterTypes, object[ ] positionalParameterValues )