问题
There is an extension to Entity Framework called Future Queries that allows queries to be batched up and processed at the same time.
For example, from their docs:
// build up queries
var q1 = db.Users
.Where(t => t.EmailAddress == "one@test.com")
.Future();
var q2 = db.Tasks
.Where(t => t.Summary == "Test")
.Future();
// this triggers the loading of all the future queries
var users = q1.ToList();
Is there any equivalent in NHibernate, or an extension that might give this type of functionality?
回答1:
Yes, there is a such feature. Best if you'll read:
Ayende's NHibernate Futures
Small cite:
One of the nicest new features in NHibernate 2.1 is the
Future<T>()
andFutureValue<T>()
functions. They essentially function as a way to defer query execution to a later date, at which point NHibernate will have more information about what the application is supposed to do, and optimize for it accordingly. This build on an existing feature of NHibernate, Multi Queries, but does so in a way that is easy to use and almost seamless.
Some example from that article:
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();
}
回答2:
To expand on @Radim's answer, here's what the equivalent code would look like, using LINQ to NHibernate:
IEnumerable<Users> users = session.Query<Users>()
.Where(p => p.EmailAddress == "one@test.com")
.ToFuture();
IEnumerable<Tasks> tasks = session.Query<Tasks>()
.Where(p => p.Summary == "Test")
.ToFuture();
As you'd expect, both queries will be batched and executed when either needs to be processed.
来源:https://stackoverflow.com/questions/25061552/nhibernate-equivalent-of-entity-framework-future-queries