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


Question

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.

Accepted Answer

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();

Popular Answer

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.





Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why