Average
This method is used to compute the average value of the target field.
Code Snippets
Below is the sample code that averages the column Value
from a [dbo].[Sales]
table for a specific customer since yesterday.
using (var connection = new SqlConnection(connectionString))
{
var customerExpenses = connection.Average<Sales>(e => e.Value,
e => e.CustomerId == 10045 && e.DateInsertedUtc >= DateTime.UtcNow.Date.AddDays(-1));
}
Targeting a Table
You can also target a specific table by passing the literal table and field name like below.
using (var connection = new SqlConnection(connectionString))
{
var customerExpenses = connection.Average("[dbo].[Sales]", Field.From("Value"), new { State = "Michigan" });
}
Or, use the QueryGroup or QueryField if you are to enhance the WHERE expressions.
using (var connection = new SqlConnection(connectionString))
{
var where = new []
{
new QueryField("CustomerId", 10045),
new QueryField("DateInsertedUtc", Operation.GreaterThanOrEqual, DateTime.UtcNow.Date.AddDays(-1))
}
var customerExpenses = connection.Average("[dbo].[Sales]", Field.From("Value"), where);
}
Table Hints
To pass a hint, simply write the table-hints and pass it in the hints
argument.
using (var connection = new SqlConnection(connectionString))
{
var customerExpenses = connection.Average<Sales>(e => e.Value,
e => e.CustomerId == 10045 && e.DateInsertedUtc >= DateTime.UtcNow.Date.AddDays(-1),
hints: "WITH (NOLOCK)");
}
Or, you can use the SqlServerTableHints class.
using (var connection = new SqlConnection(connectionString))
{
var customerExpenses = connection.Average<Sales>(e => e.CustomerId == 10045 && e.DateInsertedUtc >= DateTime.UtcNow.Date.AddDays(-1),
hints: SqlServerTableHints.NoLock);
}