简体   繁体   中英

LINQ select new Async/Await

I currently have a asynchronous query as follows which is fine and allows me to use the FirstOrDefaultAsync / ToListAsync methods.

 public async Task<X> FindXAsync(int x)
 {
      var q = from c in context.X
              where c.Id == x
              select c;

      return await q.FirstOrDefaultAsync();
 }

However I am attempting to extend that query to select into a new class

public async Task<XClass> FindXAsync(int x)
{
     var q = from c in context.X
            where c.Id == x
            select new XClass (
            c.Id,c.Header .........
            );

     return await q.FirstOrDefaultAsync();
}

For the above you can no longer use the FirstOrDefaultAsync() only FirstOrDefault(), I was wondering what would be the most efficient way to get this functionality into an asynchronous method. Thanks, Chris

In this case, the easiest answer is probably just to do the (asynchronous) first selection, and then create the type you need:

public async Task<XClass> FindXAsync(int x)
{
  var q = from c in context.X
          where c.Id == x
          select c;
  var c = await q.FirstOrDefaultAsync();
  return new XClass (
           c.Id,c.Header .........
  );
}

尝试使用通用类型化参数:

return await q.FirstOrDefaultAsync<XClass>();

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