How do you catch the Save or Load event in the Linq-to-SQL class?

I have a Linq-to-SQL class, and I would like to do a preliminary check before the record is saved to the database. In addition, as soon as it is saved, I would like to have a processing code after saving.

Similarly, when a record is deleted, I would like to have preliminary and post methods that will be called, regardless of where the call is made context.SubmitChanges().

I do not see any methods in the generated code that I can override. A partial method OnValidate()may be sufficient for preprocessing, but I want to cancel the save if certain conditions are not met, and I do not see any intercepts for further processing.

Am I missing something? Or can you recommend another way to achieve the intended effect?

Thanks!

+5
source share
2 answers

For inserts:

  • Create a base class for your objects.

  • Add some virtual methods.

  • Override DataContext.SubmitChanges.

  • Call DataContext.GetChangeSet()and iterate over inserts using a previously defined function.

To revert the changes, review the extension method .

+7
source

Well, throwing an exception will actually reverse the change ... a little harsh, though, perhaps.

SubmitChanges , (GetChangeSet), (, ), base.SubmitChanges. ( , ).

+4

All Articles