Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 - how to convert this line to async?

I am wondering how do I change this statement to be async?

    var findBarCode = context.Barcodes
        .Where(x => x.Code == barcode)
        .Select(x => x.Product).FirstOrDefault();

I don't see like any async where statement I can use.

like image 647
chobo2 Avatar asked May 19 '13 19:05

chobo2


People also ask

What do I replace IQueryable with for async operations?

AsQueryable()); c# linq.

What does SaveChangesAsync return?

SaveChangesAsync() returns the number of lines changed. It is possible (at least theoretically) that two user will simultenously work to delete the same id in the database.

Can IQueryable be async?

ToListAsync(IQueryable)Creates a List<T> from an IQueryable by enumerating it asynchronously.

What does FirstOrDefaultAsync return?

FirstOrDefaultAsync<TSource>(IQueryable<TSource>, CancellationToken) Asynchronously returns the first element of a sequence, or a default value if the sequence contains no elements.


1 Answers

There's an extension method called FirstOrDefaultAsync in System.Data.Entity:

using System.Data.Entity;
...
var findBarCode = await context.Barcodes
    .Where(x => x.Code == barcode)
    .Select(x => x.Product).FirstOrDefaultAsync();

This requires Entity Framework 6.0.

like image 192
Aske B. Avatar answered Oct 18 '22 17:10

Aske B.