Show Progressbar when loading data using EntityFrameWork in WPF

醉酒当歌 提交于 2021-01-28 06:08:09

问题


I want to show the progress of Data being fetched from Database in a Progressbar. Currently i am updating the content of a Button. Have no idea how to implement in this code .

private async void FetchInvoicesDataFunc(object sender, RoutedEventArgs e)
 {
   ProgressBtn.Content = "Loading Data ...";
   InvoiceGrid.ItemsSource = await  Task.Run(FetchInvoiceDataAsync);
   ProgressBtn.Content = "Loaded !";

 }

private async Task<List<Invoice>> FetchInvoiceDataAsync()
 {
   List<Invoice> result;
   using(var context = new Intelliventory_DBEntities() )
    {  
      result  = await context.Invoices.Where(b => b.InvoiceID <= 2000).Include(x => x.Customer).ToListAsync();      
    }
        return  result;
    }
}

回答1:


You won't be able to show the percentage of an EF-Query, as it doesn't notify you about the progress of the DB query (I don't know any DB-System that keeps the client informed about the status of a query)

You could consider splitting your query into pieces like this:

 private async void FetchInvoicesDataFunc(object sender, RoutedEventArgs e)
 {
   List<Invoice> results = new List<Invoice>();
   ProgressBtn.Content = "Loading Data ...";
   await Task.Run(async() => results.AddRange(await FetchInvoiceDataAsync(0, 500));  
   ProgressBtn.Content = "25% done...";
   await Task.Run(async() => results.AddRange(await FetchInvoiceDataAsync(501, 1000)); 
   ProgressBtn.Content = "50% done...";
   await Task.Run(async() => results.AddRange(await FetchInvoiceDataAsync(1001, 1500)); 
   ProgressBtn.Content = "75% done...";
   await Task.Run(async() => results.AddRange(await FetchInvoiceDataAsync(1501, 2000));        
   InvoiceGrid.ItemsSource = results;
   ProgressBtn.Content = "Loaded !";    
 }

 private async Task<List<Invoice>> FetchInvoiceDataAsync(int start, int end)
 {
   List<Invoice> result;
   using(var context = new Intelliventory_DBEntities() )
   {  
     result  = await context.Invoices.Where(b => b.InvoiceID >= start && b.InvoiceID <= end).Include(x => x.Customer).ToListAsync();      
   }

   return  result;
 }

Please note that this will have a negative impact on the performance of your application. There are thousands of tutorials how to use progressbars both in WinForms and WPF so i won't dive into that topic.



来源:https://stackoverflow.com/questions/51954554/show-progressbar-when-loading-data-using-entityframework-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!