Search code examples
sql-serverajaxdatabaseentity-frameworkprogress

How can I know the progress of a query execution using Entity Framework?


 public ActionResult SearchBook(BookSearchModel model)
    {
        using(var db = new BooksEntities())
        {
            var bookName = db.bookTables.Where(m => m.bookName == model.bookName).ToList();
            if(bookName.Count >= 1)
            {
                foreach (var book in bookName)
                {
                    model.bookName = book.bookName;
                }
            }
            else
            {
                model.bookName = "Cannot Find Book";
            }               
        }
        return Json(model.bookName);
    }

I have this code here which retrieves an item from the database which matches a certain criteria. What i want to add to this is to retrieve the progress of how far, percentage wise, it is through completing the database search. My overall aim is to create a progress bar which realistically simulates how long is left till the search is completed.

I am using MVC and entity framework.


Solution

  • You could restructure your code to first request a Count of total items, and then create your own loop using .Skip and .Take to send multiple requests, updating the progress bar each time you get closer to the count, as in this pseudo-code:

    int count = db.bookTables.Count() / 100;
    ProgressBar.maxValue = count;
    for (int i = 0; i < count; i++)`
        db.bookTables.Where(...).Skip(100 * i).Take(100);
        ProgressBar.Value = i;
    

    I'd recommend against this though - it won't perform as well as just making the query, and to be honest if your query is taking long enough that you'd want a progress bar you might want to consider reworking it - can you optimize your query at all so that it will run more quickly? Can you implement some kind of Lazy Loading pattern to only get the part of the data you really want to present to the user at this time, and load the rest later if the user needs it?

    One other possibility is to implement some kind of progress logic in your existing foreach loop - turn it into a for loop and update a progress bar value there, like so:

    int i = 0;
    foreach (var book in bookName)
    {
      ProgressBar.Value = i++;
      model.bookName = book.bookName;
    
    }