ISqlModelMapper.Sum<TModel>(string expression, params object[] parameters) Method
.NET Standard 2.x
Computes the sum of the value using the specified SQL expression for the data retrieved according to the criteria specified in a TModel
class.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public object Sum<TModel>(string expression, params object[] parameters);
Type Parameters
TModel
The type of a model class.
Parameters
expression
System.String
A string of SQL expression used to compute the sum of the value.
parameters
System.Object[]
(Optional) One or more values that you want to use as retrieval arguments in the SQL SELECT statement defined in TModel
.
Returns
System.Object
The sum of the value of the retrieved data. Its data type is determined by the return value of the SQL expression.
Remarks
The expression
parameter contains the string of a SQL expression which will be used by the SQL AVG()
function, therefore, the SQL expression string must comply with the SQL conventions, otherwise, exceptions may be thrown.
This method only returns the data of the first column in the first row of the retrieved data, therefore, please avoid using this method when groups are defined in TModel
.
Examples
The following code example demonstrates how to calculate the sum of the budgets for all departments.
using Appeon.ApiDoc.Models.School;
using System;
namespace Appeon.ApiDoc.ISqlModelMapperExamples
{
public class SumExample
{
private SchoolContext _context;
public SumExample(SchoolContext dataContext)
{
// Sets the data context.
_context = dataContext;
}
public void Example()
{
var mapper = _context.SqlModelMapper;
// Calculates the sum of the budgets.
decimal sumBudget = (decimal)mapper.Sum<Department>("Budget");
Console.WriteLine("The sum of the budgets is {0}.",
sumBudget.ToString("N0"));
// Loads all records to show budgets.
var depts = mapper.Load<Department>().ToList();
Console.WriteLine();
Console.WriteLine("The budgets for all departments:");
foreach (var dept in depts)
{
Console.WriteLine(dept.Name + " " + dept.Budget.ToString("N0"));
}
/* The code produces the following output:
The sum of the budgets is 920,000.
The budgets for all departments:
Engineering 350,000
English 120,000
Economics 200,000
Mathematics 250,000
*/
}
}
}
Example Refer To
Model Class: Department
Applies to
.NET Standard
2.x