await/async Microsoft Practices Enterprise Library Data
I'm using an older version of the EL that offers Begin* / End* methods, but not async versions. Some simple extension methods simplify life:
public static async Task<IDataReader> ExecuteReaderAsync(this SqlDatabase database, DbCommand command)
{
return await Task<IDataReader>.Factory.FromAsync(database.BeginExecuteReader, database.EndExecuteReader, command, null);
}
public static async Task<object> ExecuteScalarAsync(this SqlDatabase database, DbCommand command)
{
return await Task<object>.Factory.FromAsync(database.BeginExecuteScalar, database.EndExecuteScalar, command, null);
}
public static async Task<XmlReader> ExecuteXmlReaderAsync(this SqlDatabase database, DbCommand command)
{
return await Task<XmlReader>.Factory.FromAsync(database.BeginExecuteXmlReader, database.EndExecuteXmlReader, command, null);
}
public static async Task<int> ExecuteNonQueryAsync(this SqlDatabase database, DbCommand command)
{
return await Task<int>.Factory.FromAsync(database.BeginExecuteNonQuery, database.EndExecuteNonQuery, command, null);
}
I actually was able to find the Async methods. I was just looking in the wrong spots. Here's two common ways of accessing the DB asynchronously:
var db = DatabaseFactory.CreateDatabase(GlobalConstants.DBConnection);
using (var cmd = db.GetStoredProcCommand("SprocName", parameterA))
{
await cmd.ExecuteNonQueryAsync();
}
and when you want to get data:
var db = DatabaseFactory.CreateDatabase(GlobalConstants.DBConnection);
using (var cmd = db.GetStoredProcCommand("SprocName", parameterA, parameterB, parameterC))
{
using (var dr = await cmd.ExecuteReaderAsync())
{
while (await dr.ReadAsync())
{
return dr.GetInt32(0);
}
}
}
You can use GetFieldValueAsync<T>
instead of GetInt32
if you are using CommandBehavior.SequentialAccess
with large amounts of data. But, for most cases, you probably do not need to do this.