从对象获取值或执行其他查询有什么区别吗?
我使用 nhibernate 和流畅的 nhibernate。
我想知道这两种方式有什么区别吗?
- 执行查询以从数据库获取对象集合(例如公司集合)。
- 现在我需要获取另一个产品引用的表(比如产品)。
选项 1
var companies = session.Query<Companies>().ToList();
companies.Where(x => x.products.Id == 1).toList();
所以我正在过滤结果对象。我会与所有公司一起做一些事情,但稍后我需要对其进行更多过滤以做其他一些事情
选项 2.
一起进行另一个 nhiberante 查询。
var companies = session.Query<Companies>().ToList();
var products = session.Query<Companies>().Where(x => x.products == 1).ToList();
我猜如果我获取/急切加载所有内容,那么会有差异(在性能、查询数量等方面)。
但如果我是延迟加载呢?
I am use nhibernate with fluent nhibernate.
I wondering if there is any difference between these 2 ways.
- Do a query to get an collection of objects from the db(say collection of companies).
- Now I need to get another table that products references(say products).
Option 1
var companies = session.Query<Companies>().ToList();
companies.Where(x => x.products.Id == 1).toList();
So I am filtering on result object. I would be doing something with all the companies but later on I need to filter it down some more to do some other stuff
Option 2.
do another nhiberante query all together.
var companies = session.Query<Companies>().ToList();
var products = session.Query<Companies>().Where(x => x.products == 1).ToList();
I am guessing if I fetch/eager load everything then there would be a difference(in performance,number of queries and etc).
But how about if I am lazy loading?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设您希望第二个查询过滤具有 Id == 1 的
Product
的Companies
。那么您的查询实际上应如下所示:选项 1:
选项 2 :
在延迟加载的情况下,选项1将导致N+1问题,因为NHibernate将不得不查询
IList;列表中每个发票的产品
。在大多数情况下,这将比选项 2 慢得多,其中 NHibernate 将能够使用EXISTS
子查询在单个查询中完成整个操作。I assume that you want the second query to filter the
Companies
that have aProduct
with Id == 1. Then your queries should actually look like this:Option 1:
Option 2:
In the case of lazy loading, option 1 will result in a N+1 problem, because NHibernate will have to query the
IList<Product> Products
for each Invoice in the list. In most scenarios that will be much slower than option 2 where NHibernate will be able to do the whole thing in a single query, using anEXISTS
subquery.我认为你的代码有错误。不应该是:
和吗
?
尽管如此,答案并不明确。这是因为,是否需要大量查询产品实际上取决于您的判断。我会启动 sql profiler,并在单元测试期间比较这两种方法。
但为了至少有一点帮助,我通常使用选项 2。我仅在特定情况下选择选项 1。
I think you have mistakes in code. Shouldn't it be:
and
?
Even though, the answer is not unequivocally. That's because it's really up to you to judge if you will need to heavily query products or not. I would fire sql profiler and just compare both approaches during unit tests.
But trying to be helpful at least a little bit, I'm usually using Option 2. I choose Option 1 only in specific scenarios.