ISqlModelMapper.ScalarByKeyAsync<TModel, TValue>(string expression, object[] parameters, CancellationToken cancellationToken) Method
.NET Standard 2.x
Asynchronously retrieves data from the first column, in the first row, for the specified SQL expression according to the primary key in a TModel
class.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public Task<TValue> ScalarByKeyAsync<TModel, TValue>(string expression, object[] parameters, CancellationToken cancellationToken)
Type Parameters
TModel
The type of a model class.
TValue
The type of the value retrieved.
Parameters
expression
System.String
A SQL expression string used to get data from the first column in the first row.
parameters
System.Object[]
(Optional) One or more values that you want to use as retrieval arguments in the SQL SELECT statement defined by the primary table and the primary key(s) in TModel
.
cancellationToken
CancellationToken
(Optional) A cancellation token that can be used by other objects or threads to receive notice of cancellation.
Returns
Task<TValue>
Returns a task that represents the asynchronous operation.
Remarks
At least one data row must be retrieved by the specified criteria, otherwise exceptions will be thrown.
Examples
The following code example demonstrates how to get the budget asynchronously for the department of Economics. It uses a CancellationTokenSource type parameter to make this operation cancelable.
using System;
using System.Threading;
using System.Threading.Tasks;
using Appeon.ApiDoc.Models.School;
using SnapObjects.Data;
namespace Appeon.ApiDoc.ISqlModelMapperExamples
{
public class ScalarByKeyAsyncExample
{
private readonly SchoolContext _context;
public ScalarByKeyAsyncExample(SchoolContext dataContext)
{
// Sets the data context.
_context = dataContext;
}
public async Task<decimal> Example2(CancellationTokenSource cts)
{
decimal budget = 0m;
try
{
// Asynchronously gets the budget for the department of Economics according to the key.
// If a task has been cancelled, the call to the ISqlModelMapper.ScalarByKeyAsync
// method throws an OperationCanceledException.
budget = await _context.SqlModelMapper
.ScalarByKeyAsync<Department, decimal>("Budget",
new object[] { 4 }, cts.Token);
Console.WriteLine("The budget of the department of Economics {0}.",
budget.ToString("N0"));
}
catch (OperationCanceledException e)
{
// The operation was cancelled before completion.
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
cts.Dispose();
}
return budget;
/* The code produces the following output:
A task was canceled.
*/
}
}
}
Applies to
.NET Standard
2.x