QueryableExtensions.FirstOrDefaultAsync<TSource> Method (IQueryable<TSource>, CancellationToken)

[This page is specific to the Entity Framework version 6. The latest version is available as the 'Entity Framework' NuGet package. For more information about Entity Framework, see msdn.com/data/ef.]

Asynchronously returns the first element of a sequence, or a default value if the sequence contains no elements.

Namespace:  System.Data.Entity
Assembly:  EntityFramework (in EntityFramework.dll)

Syntax

'Declaration
<ExtensionAttribute> _
Public Shared Function FirstOrDefaultAsync(Of TSource) ( _
    source As IQueryable(Of TSource), _
    cancellationToken As CancellationToken _
) As Task(Of TSource)
'Usage
Dim source As IQueryable(Of TSource)
Dim cancellationToken As CancellationToken 
Dim returnValue As Task(Of TSource)

returnValue = source.FirstOrDefaultAsync(cancellationToken)
public static Task<TSource> FirstOrDefaultAsync<TSource>(
    this IQueryable<TSource> source,
    CancellationToken cancellationToken
)
[ExtensionAttribute]
public:
generic<typename TSource>
static Task<TSource>^ FirstOrDefaultAsync(
    IQueryable<TSource>^ source, 
    CancellationToken cancellationToken
)
static member FirstOrDefaultAsync : 
        source:IQueryable<'TSource> * 
        cancellationToken:CancellationToken -> Task<'TSource> 
JScript does not support generic types and methods.

Type Parameters

  • TSource
    The type of the elements of source.

Parameters

Return Value

Type: System.Threading.Tasks.Task<TSource>
A task that represents the asynchronous operation. The task result contains default ( TSource ) if source is empty; otherwise, the first element in source.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IQueryable<TSource>. When you use instance method syntax to call this method, omit the first parameter. For more information, see https://msdn.microsoft.com/en-us/library/bb384936(v=vs.113) or https://msdn.microsoft.com/en-us/library/bb383977(v=vs.113).

Exceptions

Exception Condition
ArgumentNullException

source is null .

InvalidOperationException

source does not implement IDbAsyncQueryProvider .

Remarks

Multiple active operations on the same context instance are not supported. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context.

See Also

Reference

QueryableExtensions Class

FirstOrDefaultAsync Overload

System.Data.Entity Namespace