Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Linq2Sql before SubmitChanges()

Can anyone tell me if/how you can validate the changes in a data context in Linq2Sql before calling SubmitChanges(). The situation I have is that I create a context, perform multiple operations and add many inserts alongside other processing tasks and then rollback if the submit fails.

What I'd prefer to do is make some kind of "Validate()" call after certain tasks are done so that I can handle it before submitting the entire job.

like image 806
Nick Gotch Avatar asked Jul 31 '09 14:07

Nick Gotch


1 Answers

To get all the changes in a data context you can call

ChangeSet changes = dataContext.GetChangeSet();

// An IList<Object>
changes.Deletes;
changes.Inserts;
changes.Updates;

What I have is each value object has a validate method. I use attibutes to define different sorts of validation. The reason I do it manually is because an I have a number that maybe an int in the database and the code, a value of 1002 could be invalid if I saving a age. So I can give a range of values, etc. . .

If each of your value objects inherit from a base object it makes iterating them easier. Assuming you have on your base class a Validate method.

I would point out for this to work, you are going to have to either edit the generated code, or roll your own value objects. I typically roll my own because of how I use them for validation.

like image 176
David Basarab Avatar answered Oct 30 '22 16:10

David Basarab