0

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

Chris
  • 915
  • 8
  • 28

2 Answers2

3

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 .........
  );
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thanks Stephen, realized the problem after reading the comments but thanks for the answer. p.s. Concurrency In C# Cookbook was an excellent reference book for starting to work with asynchronous programming. – Chris Mar 10 '16 at 12:04
  • On a side note how would this work with the result of a stored procedure as the result is an IEnumerable ? – Chris Mar 10 '16 at 12:13
  • @Chris: I don't have much experience with sprocs, but I believe it should work fine; it would be exposed as an IQueryable over the network and I'd expect EF's `FirstOrDefaultAsync` to work. – Stephen Cleary Mar 10 '16 at 12:41
1

Try it with generic typed parameter:

return await q.FirstOrDefaultAsync<XClass>();
Mihail Stancescu
  • 4,088
  • 1
  • 16
  • 21