Sum
This method computes the sum of the target field.
This method computes the sum of the target field.
Code Snippets
The following example returns the sum of the Value column from the [dbo].[Sales] table for a specific customer since yesterday.
using (var connection = new SqlConnection(connectionString))
{
var customerExpenses = connection.Sum<Sales>(e => e.Value,
e => e.CustomerId == 10045 && e.DateInsertedUtc >= DateTime.UtcNow.Date.AddDays(-1));
}
Targeting a Table
To target a specific table, pass the literal table and field name.
using (var connection = new SqlConnection(connectionString))
{
var customerExpenses = connection.Sum("[dbo].[Sales]",
Field.From("Value"), new { State = "Michigan" });
}
Use QueryGroup or QueryField to build more complex 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.Sum("[dbo].[Sales]", Field.From("Value"), where: where);
}
Table Hints
Pass a table hint via the hints argument.
using (var connection = new SqlConnection(connectionString))
{
var customerExpenses = connection.Sum<Sales>(e => e.Value,
e => e.CustomerId == 10045 && e.DateInsertedUtc >= DateTime.UtcNow.Date.AddDays(-1),
hints: "WITH (NOLOCK)");
}
Or use the SqlServerTableHints class.
using (var connection = new SqlConnection(connectionString))
{
var customerExpenses = connection.Sum<Sales>(
e => e.CustomerId == 10045 && e.DateInsertedUtc >= DateTime.UtcNow.Date.AddDays(-1),
hints: SqlServerTableHints.NoLock);
}