The autogenerated classes that derive from DataContext
are not intended to be long-lived objects. In the vast majority of use-cases, you are supposed to instantiate one, read the data you need and/or make the changes you need, submit, and then forget about the object. It does not directly represent a connection to the database — instantiating lots of DataContext
s does not necessarily open multiple connections to the DB.
The consequence of this is that you should consider your data to be always stale, especially if a separate process can access the same database. As soon as you’ve retrieved data, the other process could immediate update that data. The only way to ensure non-staleness is to maintain an open transaction, and as I’m sure you know, the ramifications of keeping a transaction open for too long is that the other process will find the database to be highly unresponsive, as if it were extremely slow — so only use a transaction for a processing step that involves pretty much only DB access that needs to be atomic.
Thus, in your specific case, the only way to find out whether there are any new actions to be performed is to keep asking the database. You don’t have to keep retrieving the data and compare it using Equals; you can just retrieve all the data you haven’t already got, i.e. tell the database to return only the new rows. Since I don’t know your database schema, I’m making things up here, but I’m sure this will give you an idea:
var newActions = db.ScheduledActions.Where(act => !oldActions.Contains(act)).ToList();
if (newActions.Any()) {
// ... do something intelligent with the new actions ...
oldActions = oldActions.Concat(newActions);
// or perhaps oldActions.AddRange(newActions); if oldActions is a List<>
}
Edit: I realise now that you need to check not only for new actions, but also for changes to existing actions. Personally the way I would implement this is by having a date/time field on the ScheduledActions table that specifies the time of the last change. Then you don’t need a custom equality comparer, but instead you can use that to find out what’s changed. Unfortunately, it means that you need to retrieve all the actions, even the ones that haven’t changed. In the following example, I assume that ScheduledActions are identified by a primary key of type string
; change that to int
if you’re using numeric keys:
Dictionary<string, ScheduledAction> oldActions = new ...;
[...]
var allActions = db.Actions.ToList();
var changedActions = allActions.Where(act => !oldActions.ContainsKey(act.Id) || oldActions[act.Id].LastChanged < act.LastChanged).ToList();
if (changedActions.Any())
{
// do something intelligent here
}