Asynchronous method, which includes asynchronous call and synchronization of actions according to the result

I am trying to make an asynchronous method that I can call several times and wait later - the method should make a database call, wait for the results, do some manipulation after receiving the results, and then return the final result. It looks like this:

public async Task<long> GetSomethingFromDbAndSelectSomethingOnServer() { //stuff is just an Entity Framework database call var stuff = await myEfDbContext.StuffTable.ToListAsync(); long itemsCount = stuff.Where(someQueryThatCantGoToDb).Count(); return itemsCount; } 

This seems like a blatant mistake, since I specify the return type as "Task", while I actually return just for a long time. This compiles, but throws an exception:

The first exception of type 'System.NotSupportedException' exception occurred in EntityFramework.dll

I plan to use this code like this:

 Task<long> myAsyncCall = GetSomethingFromDbAndSelectSomethingOnServer(); long myCount = await myAsyncCall; 

This might be a little out of place, but for development, here is something good that works:

 Task<long> pendingItemCountCall = _mongoItems.Find(filter).CountAsync(); long myCount2 = await pendingItemCountCall; 

The difference, of course, is that it is just an asynchronous db call without further action that I am trying to make in the SQL call that I am asking this question about.

EDIT:

So this actually seems to be a violation:

 var stuff = await myEfDbContext.StuffTable.ToListAsync(); 

If I comment on this and set the var score manually, the code goes. I'm rather confused, but I'm more interested in the general question: am I using the asynchronous code correctly here, and not necessarily an error for my specific error.

0
c # asynchronous entity-framework
Mar 07 '16 at 15:39
source share
1 answer

You cannot wait for multiple requests in the same context. You must use your own context for each operation:

 public async Task<long> GetSomethingFromDbAndSelectSomethingOnServer() { using(var context = new MyEfDbContext()) { // include the following if you do not need lazy loading and want some more speed context.Configuration.AutoDetectChangesEnabled = false; context.Configuration.ProxyCreationEnabled = false; var stuff = await myEfDbContext.StuffTable.ToListAsync(); long itemsCount = stuff.Where(someQueryThatCantGoToDb).Count(); return itemsCount; } } 
+3
Mar 07 '16 at 15:52
source share



All Articles