7

I'm using EF 6.1.1 and Database First. When I import a stored proc into the edmx and generate the DBContext it looks like this:

return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<TestSP_Result>("TestSP", params[]...)

That returns an ObjectResult< T >, which implements IDbAsyncEnumerable< T > so I'm doing this to read the data async:

 IDbAsyncEnumerable<T> enumerable = objectResult as IDbAsyncEnumerable<T>;
 IDbAsyncEnumerator<T> enumerator = enumerable.GetAsyncEnumerator();
 List<T> list = new List<T>();
 bool moreItems = await enumerator.MoveNextAsync(CancellationToken.None);

 while (moreItems)
 {
     list.Add(enumerator.Current);
     moreItems = await enumerator.MoveNextAsync(CancellationToken.None);
 }
 return list;

Is this really reading the data asynchronously? I attached the profiler and the actual SQL statement runs in the ExecuteFunction line, not when enumerating the results.

Is there a proper way to run a stored proc from the DBContext and read the results asynchronously?

oscarmorasu
  • 901
  • 3
  • 11
  • 28
  • Here is another way to accomplish what your trying to do. http://stackoverflow.com/questions/19250599/how-do-i-kick-off-an-entity-stored-procedure-in-ef6-async-and-not-wait-for-a-ret – Jason Foglia Jun 03 '15 at 15:44
  • @JasonFoglia, FYI: All that linked solution does is queue up synchronous work on another threadpool thread, it doesn't accomplish what was being asked. – TravisWhidden Aug 17 '15 at 18:12

1 Answers1

15

How I do it:

var results = await ctx.Database.SqlQuery<TResult>("EXEC sp_foo {0}, {1}", p1, p2)
                  .ToArrayAsync();
Cory Nelson
  • 29,236
  • 5
  • 72
  • 110