zeqk
7/5/2018 - 1:33 PM

This gist shows how to use the NHibernate async API

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