ISqlModelMapper.LoadByKeyAsync<TModel>(object[] parameters, CancellationToken cancellationToken) Method
.NET Standard 2.x
Asynchronously retrieves data according to the primary key defined in a TModel
class.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public Task<ILoadable<TModel>> LoadByKeyAsync<TModel>(object[] parameters, CancellationToken cancellationToken)
Type Parameters
TModel
The type of a model class.
Parameters
parameters
System.Object[]
One or more values that you want to use as retrieval arguments in the SQL SELECT statement defined by the primary table and its primary key(s) in TModel
.
cancellationToken
CancellationToken
A cancellation token that can be used by other objects or threads to receive notice of cancellation.
Returns
Task<ILoadable<TModel>>
Returns a task that represents the asynchronous operation.
Remarks
If the SQL query defined in TModel
makes query from multiple tables, then this method only retrieves and loads data from the primary table.
If TModel
has properties that apply attributes such as SqlCompute, NotMapped
etc., LoadAll and LoadByKey cannot load data of such properties. In such case, use Load instead of LoadAll and LoadByKey.
Examples
The following code example demonstrates how to load the department asynchronously according to the key. 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;
namespace Appeon.ApiDoc.ISqlModelMapperExamples
{
public class LoadByKeyAsyncExample
{
private readonly SchoolContext _context;
public LoadByKeyAsyncExample(SchoolContext dataContext)
{
// Sets the data context.
_context = dataContext;
}
public async Task<Department> Example2(CancellationTokenSource cts)
{
var mapper = _context.SqlModelMapper;
Department engineering = null;
try
{
// Asynchronously loads the department of Engineering according to the key
// (Department ID = 1).
// If a task has been cancelled, the call to the ISqlModelMapper.LoadAsync
// method throws an OperationCanceledException.
engineering = (await mapper.LoadByKeyAsync<Department>(
new object[] { 1 }, cts.Token )).FirstOrDefault();
Console.WriteLine("The department of Engineering:");
Console.WriteLine("Department ID is {0}",
engineering.DepartmentID);
Console.WriteLine("Name is {0}",
engineering.Name);
Console.WriteLine("Budget is {0}",
engineering.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 engineering;
/*The code produces the following output:
A task was canceled.
*/
}
}
}
Applies to
.NET Standard
2.x