chobo2
chobo2

Reputation: 85835

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.

Upvotes: 20

Views: 16819

Answers (2)

Aske B.
Aske B.

Reputation: 6609

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.

Upvotes: 39

Andrei Drynov
Andrei Drynov

Reputation: 8592

What about SingleAsync or FindAsync? Not sure about FirstOrDefault one

Do use await.

var findBarCode = await context.Barcodes
        .Where(x => x.Code == barcode)
        .SingleAsync(x => x.Product);

Another way (might silly as I have no access to VS at present):

 var findBarCode = await context.Barcodes
            .Where(x => x.Code == barcode)
            .OrderBy(YOURCRITERIA)
            .Take(1)
            .Select(x => x.Product)
            .ToListAsync();

Upvotes: 15

Related Questions