views:

63

answers:

2

I have a Linq-to-SQL class, and I'd like to perform some pre-save validation before the record is persisted to the DB. In addition, once it has been saved, I'd like to have some post-save processing code.

Similarly, when a record is deleted, I'd like to have pre- and post- methods that will be called, no matter from where the context.SubmitChanges() call is made.

I don't see any methods in the generated code that I can override. The partial method OnValidate() may be sufficient for the pre-processing, but I want to ability to cancel the save if certain conditions are not met, and I don't see any hooks at all for post-processing.

Am I missing something? Or can you recommend another way of achieving the intended effect?

Thanks!

+2  A: 

Well, throwing an exception will effectively cancel the change... a bit harsh though, perhaps.

Another extension point is by overriding the SubmitChanges on the data-context, to get the pending changes (GetChangeSet), do any final changes (auditing, perhaps), and then call the base.SubmitChanges. You could put any post-save operations after this (using the change-set you obtained before the save).

Marc Gravell
+3  A: 

For inserts:

  1. Create a base class for your entities.

  2. Add some virtual methods.

  3. Override DataContext.SubmitChanges.

  4. Call DataContext.GetChanges() and iterate over the inserts applying the function you defined previously.

For reverting changes, look at my extension method.

leppie
Thank you - didn't realize SubmitChanges was virtual! Between you )
Shaul