简体   繁体   中英

EF calls and returns from stored procedure fast but then converting it to list takes 20 seconds for 1000 records

I am debugging a piece of code which is using EF as ORM. Now, I am seeing somewhat interesting behavior from the application:

This is the code where I'm calling a stored procedure:

List<RequestListEntity> results = new List<RequestListEntity>();
var temp = System.Data.Object.ObjectContext.ExecuteFunction<T>("storedProcedure", param);

foreach (var item in temp)
{
    results.Add(item);
}

Observations:

  1. When I run the stored procedure on the server, it is very fast. It has joins with tables, but it returns 1000 records within a second
  2. When I call the stored procedure from C# using the code shown above, it also returns within a second and returns objectResult<T> with a total of 1000 entries.
  3. Now when I try to iterate through the result OR try to convert the result to a List, it is hell of a lot slower.

Now this raises a lot of questions:

  1. If it returning from DB so fast then why mere conversion of 1000 records is taking so much time? Or may be it is still going back to DB for conversion?
  2. Is there anything I can do to make it fast? When it calls the function, it returns very fast.

The performance issue is because of lazy loading and object tracking. when this method called result maps to an entity type, two things happen that don't happen when context.Database.SqlQuery is executed :

  • The entities are tracked by the context's change tracker.
  • The entities perform lazy loading.

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