0

I am using a LINQ query in backgroundworker. When I run the program and execute the query it works properly. But when I change a value in table manually and run the query again this return last result to me and I should close the program and run it again to see the changes!

Please help me to resolve this problem.

clockEntities objDb = new clockEntities();
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) 
{
       var inOutList = (from may in objDb.Taradods
       where may.Date.Contains("2014/02") && may.BarCodeNo == 8011
       select may);
       this.Invoke(new MethodInvoker(delegate() { 
           dataGridView1.DataSource = inOutList.ToList(); }));
}
Dnyanesh
  • 2,265
  • 3
  • 20
  • 17
  • Check [How to clear the DataContext cache on Linq to Sql](http://stackoverflow.com/questions/2098143/how-to-clear-the-datacontext-cache-on-linq-to-sql) – Ulugbek Umirov May 05 '14 at 05:46
  • i try it but i can't use this method because when i write the "objDb." refresh method don't show in contexmenu. i add system.data.linq ,system.data.objects and System.Data.Entity to my project – user3603056 May 05 '14 at 06:24
  • What is the version of .Net? – Ulugbek Umirov May 05 '14 at 06:36
  • Boy, so many issues in a few lines of code. Firstly, contexts are not thread-safe so don't use them in multiple threads. Secondly, why do you use this construct anyway? You only *define* a query (which takes no time at all) in a separate thread and then execute it in the UI thread. Third, why do you still use this clunky backgroundworker and not TPL? Finally, why have you got a data column with string values? And then, if you mean "EF 6.1", this isn't linq-to-sql, but entity framework. As for your question: do you ever call `SaveChanges()`? – Gert Arnold May 05 '14 at 09:16

1 Answers1

0

Your DataContext is stale. Move the construction into the DoWork method: DataContext construction is very light anyway, so it will not harm performance that much.

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)  
{
    //==> Move it here     clockEntities objDb = new clockEntities();

    var inOutList = (from may in objDb.Taradods
    where may.Date.Contains("2014/02") && may.BarCodeNo == 8011
    select may);

    this.Invoke(new MethodInvoker(delegate() { 
    dataGridView1.DataSource = inOutList.ToList(); }));
}
MAXE
  • 4,978
  • 2
  • 45
  • 61
Pleun
  • 8,856
  • 2
  • 30
  • 50