views:

992

answers:

1

In my application, I extract the Data of a Linq To SQL DataContext into a dictionary for easy use like so:

Jobs = dbc.Jobs.ToDictionary(j => j.Id, j => j);

Then I bind this dictionary to a BindingSource:

bsJob.DataSource = jobManager.Jobs.Values.ToList();

I refresh the DataContext and the Dictionary regularly for when new Jobs are added to the database (whether directly through the local application or the application running on a different machine):

dbc.Refresh(RefreshMode.OverwriteCurrentValues, dbc.Job);
Jobs = dbc.Job.ToDictionary(j => j.Id, j => j);

How can I update the BindingSource to accommodate the changes as well?

+1  A: 

I don't see the relation from the Jobs class to the Customer class, so I'll assume you meant to type that and not jobManager.Customers.Values.ToList();

Assuming you already have some sort of event triggering your refresh, since you mentioned you updated "regularly", you can assign a new value to the BindingSource.DataSource property at that time just like you did originally.

dbc.Refresh(RefreshMode.OverwriteCurrentValues, dbc.Customer);
Customers = dbc.Customer.ToDictionary(c => c.Id, c => c);
bsJob.DataSource = jobManager.Jobs.Values.ToList();  //Assuming this statement was correct
Luis
Michael Barth
AFAIK... at least that's how I do it. Of course, there's usually multiple ways of doing things, some more creative that others.If it were my code, I'd just have a Jobs Property and have it refresh on get{}.private JobClass _JobList;public JobClass JobList{ get { _JobList = dbc.Jobs.ToDictionary(j => j.Id, j => j); return _JobList;} set{ _JobList = value;}}Then you can just assign that to your DataSourcebsJob.DataSource = JobList;
Luis
I used this approach before, but I thought it might be smarter to cache the Jobs until it's refreshed from the database (which happens every 30 seconds).
Michael Barth
If you're accessing the property more than once every 30 seconds then I'd only automatically load from the database if the private property is null.private JobClass _JobList;public JobClass JobList{get{if(_JobList == null) _JobList = dbc.Jobs.ToDictionary(j => j.Id, j => j);return _JobList;}set{_JobList = value;}}if you want to update the contents then assign a new value to the private property_JobList = dbc.Jobs.ToDictionary(j => j.Id, j => j);
Luis
Or I could assign null and access the Property, so I wouldn't have to know from where or how it is updated, but I could update it nevertheless. Great idea, I'll do that! Thanks.
Michael Barth
After some consideration it does not seem so great to change the behaviour of assigning null anymore, especially considering when other people work with that code. ;)
Michael Barth