gpt4 book ai didi

c# - NHibernate 中的 Future() 是什么意思?

转载 作者:行者123 更新时间:2023-11-30 14:09:20 24 4
gpt4 key购买 nike

我是 NHibernate 新手IEnumerable Future() 的描述;说了以下内容

// Summary:
// Get a enumerable that when enumerated will execute a batch of queries in
// a single database roundtrip

只是想知道这是什么意思,描述与“ future ”这个词无关

最佳答案

Future 允许在单次往返中执行两个或多个 sql,只要数据库支持。

它也几乎是透明的,因此您会希望尽可能使用 Futures。如果 NHibernate 无法在单次往返中执行查询,它将按预期执行两次或多次查询。

来自 http://ayende.com/blog/3979/nhibernate-futures

Let us take a look at the following piece of code:

using (var s = sf.OpenSession())
using (var tx = s.BeginTransaction())
{
var blogs = s.CreateCriteria<Blog>()
.SetMaxResults(30)
.List<Blog>();
var countOfBlogs = s.CreateCriteria<Blog>()
.SetProjection(Projections.Count(Projections.Id()))
.UniqueResult<int>();

Console.WriteLine("Number of blogs: {0}", countOfBlogs);
foreach (var blog in blogs)
{
Console.WriteLine(blog.Title);
}

tx.Commit();
}

This code would generate two queries to the database Two queries to the database is a expensive, we can see that it took us 114ms to get the data from the database. We can do better than that, let us tell NHibernate that it is free to do the optimization in any way that it likes

using (var s = sf.OpenSession())
using (var tx = s.BeginTransaction())
{
var blogs = s.CreateCriteria<Blog>()
.SetMaxResults(30)
.Future<Blog>();
var countOfBlogs = s.CreateCriteria<Blog>()
.SetProjection(Projections.Count(Projections.Id()))
.FutureValue<int>();

Console.WriteLine("Number of blogs: {0}", countOfBlogs.Value);
foreach (var blog in blogs)
{
Console.WriteLine(blog.Title);
}

tx.Commit();
}

Instead of going to the database twice, we only go once, with both queries at once. The speed difference is quite dramatic, 80 ms instead of 114 ms, so we saved about 30% of the total data access time and a total of 34 ms.

关于c# - NHibernate 中的 Future() 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29931080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com