c# - NHibernate Query<> 与 QueryOver<> 之间有什么区别?

标签 c# nhibernate

我刚开始在我当前的项目中使用 NHibernate(使用 SQLite),我主要使用 Query<> ,因为我熟悉在 Linq 中编写数据库查询。

当我遇到一些更复杂的查询时,我对 QueryOver<> 做了一些研究并认为它应该优于 Query<>因为 “QueryOver 语法是特定于 NH 的”。此外,似乎没有什么 Query<>可以做到吗QueryOver<>无法完成。

所以我开始替换 Query<> 的所有用法因此。不久之后,我遇到了第一个使用 Query<> 的“问题”。似乎更方便。 示例(从表 CustomNumber 中的 BillingDataEntity 列中选择最大值):

int result = Session.Query<BillingDataEntity>().Select(x => x.CustomNumber).OrderByDescending(a => a).FirstOrDefault();
int result = Session.QueryOver<BillingDataEntity>().Select(x => x.CustomNumber).OrderBy(a => a.CustomNumber).Desc.Take(1).SingleOrDefault<int>();

我不喜欢的是需要将结果显式转换为 int 并且 Query<> 版本更易于阅读。我的查询是否完全错误,或者换句话说:有更好的方法吗?

我查看了生成的 SQL 输出:

NHibernate: select billingdat0_.CustomNumber as col_0_0_ from "BillingDataEntity" billingdat0_ order by billingdat0_.CustomNumber desc limit 1
NHibernate: SELECT this_.CustomNumber as y0_ FROM "BillingDataEntity" this_ ORDER BY this_.CustomNumber desc limit @p0;@p0 = 1 [Type: Int32 (0)]

我到底在看什么?这是 NHibernate 进一步转换为实际数据库查询的“内部”(方法相关)查询吗?

最佳答案

Stackoverflow 上有很多关于 QueryOver 与 Query 的答案,但简而言之:-

QueryOver is a strongly-typed version of Criteria, and is more NHibernate specific. Pretty much anything you can do in ICriteria can be done with QueryOver. In the golden days of ICriteria NH2 you always had to cast, hence this is why now you need to cast at the end of the chain back to an int.

LINQ (Query) is a standard query method that works on IQueryable that doesn't need explicit references to NHibernate and can be considered more ORM agnostic and therefore follows the linq standard. As you rightly pointed out you do not need to cast to an int as you are selecting into the result the customNumber.

如果生成的 SQL 非常不同,我会对您的简单示例感到非常惊讶。

我是 QueryOver 的忠实粉丝,但随着 Linq 提供程序越来越成熟,我 95% 的查询都使用 Query 但对于一些 Nhibernate 特定的东西,我求助于返回到 QueryOver。无论哪种方式,我都建议使用分析工具来查看您可以接受的内容。

引用:Tradeoffsversusversus

关于c# - NHibernate Query<> 与 QueryOver<> 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15020817/

相关文章:

从 Angularjs 服务调用时,WebApi 中延迟加载的 nHibernate 对象出现 JsonSerializationException

c# - 设计一个跨平台的通信接口(interface)

c# - 如何在使用托管 ODP.NET 时从 C# 查询 LDAP 以解析 Oracle TNS 主机名?

c# - 调试时停止创建本地程序集

c# - 通过 RingCentral REST API 发送短信时出错

c# - 单元测试HQL查询

C# ExcelPackage 将单元格类型设置为数字

c# - 创建代理实例失败,出现 COMException(IIS、Windows Server 2012、NHibernate)

c# - nHibernate 的通用存储库

oracle - 我可以在不使用 where 子句的情况下创建自定义表达式吗?