简体   繁体   中英

IEnumerable<Entity>' does not contain a definition for 'GetAwaiter' for Async Task Method

I'm trying to pick 1 record from a table but the error i keep getting is

'IEnumerable' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?)

public class IntermediaryAssignment
    {   
       public string Company{get;set:}
       public string RegistrationNumber{get;set:}
       public bool Dispatched{get;set:}
    }

public async Task<IntermediaryAssignment> PickOneSticker(string company, 
                  string registrationNumber)
    {
        var db = new DatabaseContext();
        var results = await (from s in db.IntermediaryAssignment
                             where s.Dispatched == false && s.CompanyCode == 
                             company && s.RegistrationNumber ==
                              registrationNumber orderby s.StickerCode 
                             ascending select s).ToList().Take(1);
        return results.FirstOrDefault();
    }
var results = await (from s in db.IntermediaryAssignment
                         where s.Dispatched == false && s.CompanyCode == 
                         company && s.RegistrationNumber ==
                          registrationNumber orderby s.StickerCode 
                         ascending select s).FirstOrDefaultAsync();
    return results;

If your intention to take first item based on the order its best to use FirstOrDefault without ToList() & Take(1)

FirstOrDefault materialize the query and bring the first item from database.

ToList() if you need to get items based on your filter use to list.

In your current query .ToList().Take(1); The ToList() bring all data to memory and takes the first one, instead of this you can directly fetch first item from db using FirstOrDefault

var db = new DatabaseContext();
    var results = await (from s in db.IntermediaryAssignment
                         where s.Dispatched == false && s.CompanyCode == 
                         company && s.RegistrationNumber ==
                          registrationNumber orderby s.StickerCode 
                         ascending select s).ToListAsync());

    return results.FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM