Skip to content

Instantly share code, notes, and snippets.

@hoangitk
Forked from erdtsieck/UsageNHibernateAsync.cs
Created July 17, 2019 07:25
Show Gist options
  • Save hoangitk/fa0705235801bf73d3f11ccf05e6c636 to your computer and use it in GitHub Desktop.
Save hoangitk/fa0705235801bf73d3f11ccf05e6c636 to your computer and use it in GitHub Desktop.
This gist shows how to use the NHibernate async API
#region ICriteria async API
// Usage ICriteria.ListAsync<T>()
var customers = await session.CreateCriteria<Customer>().ListAsync<Customer>();
// Usage ICriteria.UniqueResultAsync<T>()
var customer = await session
.CreateCriteria<Customer>()
.Add(Restrictions.Eq("Name", "Erdtsieck"))
.UniqueResultAsync<Customer>();
// Usage ICriteria.Future<T>() (returns IAwaitableEnumerable, that has a method AsTask())
var customers = session
.CreateCriteria<Customer>()
.Future<Customer>();
var products = session
.CreateCriteria<Product>()
.Future<Product>();
foreach (var customer in await customers.AsTask()) { } // async
foreach (var product in products) { } // sync (normal)
// Usage ICriteria.FutureValue<T>() (returns IFutureValue, that has a method ValueAsync())
var customerCountFuture = session
.CreateCriteria<Customer>()
.SetProjection(Projections.Count(Projections.Id()))
.FutureValue<int>();
var productCountFuture = session
.CreateCriteria<Product>()
.SetProjection(Projections.Count(Projections.Id()))
.FutureValue<int>();
var customerCount = await customerCountFuture.ValueAsync(); // async
var productCount = productCountFuture.Value; // sync (normal)
#endregion
#region IQueryOver async API
// Usage IQueryOver.ListAsync()
var person = await session.QueryOver<Customer>().ListAsync();
// Usage IQueryOver.ListAsync<T>()
var person = await session.QueryOver<Customer>().Select(p => p.Name).ListAsync<string>();
// Usage IQueryOver.SingleOrDefaultAsync<T>()
var customer = await session.QueryOver<Customer>().SingleOrDefaultAsync();
// Usage IQueryOver.Future<T>() (returns IAwaitableEnumerable, that has a method AsTask())
var customers = session.QueryOver<Product>().Future();
var products = session.QueryOver<Product>().Future();
foreach (var customer in await customers.AsTask()) { } // async
foreach (var product in products) { } // sync (normal)
// Usage IQueryOver.FutureValue<T>() (returns IFutureValue, that has a method ValueAsync())
var customerFuture = session.QueryOver<Customer>().FutureValue();
var productFuture = session.QueryOver<Product>().FutureValue();
var customer = await customerFuture.ValueAsync(); // async
var product = productFuture.Value; // sync (normal)
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment