The scenario is simple:
The code to bind data from DB to listbox is as follows:
dbContext = new MyDBContext();
listBox1.DataSource = dbContext.Experiments.Select(a => a.Name + "," + a.ModificationDate.Second).ToList();
I have button to Add a row to DB table with code:
dbContext.Experiments.Add(new Models.Experiment()
{
CreationDate = DateTime.Now,
ModificationDate = DateTime.Now,
Description = "Test" + DateTime.Now.Second,
Name = "test" + DateTime.Now.Second
});
dbContext.SaveChanges();
Now I would like to automatically refresh positions in my listbox. What is the best approach to do that? I know that I can rewrite code from point 3 but I would like to have it all two way binding and automatically updated
I think that "data binding" is a keyword here. Generally in WinForms two way bidning is provided by classes like BindingList<T> or BindingSource. The question is how to use them together with EF. I think that an extension method ToBindingList can be useful here. However, I don't have a lot of experience with using it. I suggest you to look at the following article: Entity Framework Databinding with WinForms. Besides, if you search for ToBindingList EntityFramework on stackoverflow you will find many related questions.
UPDATE
I made a small test and I see a potential problem. The automatic synchronization between a control and EF will work if you use the same data context (the same instance of DbContext class). It means that a context may have a long life-cycle what is not recommended.