Nick Gotch
Nick Gotch

Reputation: 9417

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.

Upvotes: 6

Views: 1840

Answers (2)

BrandonB
BrandonB

Reputation: 113

You can also use the OnValidate() function with the LINQ-to-SQL Entity's partial class. OnValidate() will then be called during SubmitChanges() but before the data is sent to the database. One nice thing with OnValidate() is that you can differentiate between the CRUD action by the ChangeAction enumeration.

For example,

public partial class YourEntity
{
    partial void OnValidate(System.Data.Linq.ChangeAction action)
    {
        if(action == System.Data.Linq.ChangeAction.Insert)
           // Do insert
        ... etc. ...
    }
}

Upvotes: 5

David Basarab
David Basarab

Reputation: 73351

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.

Upvotes: 6

Related Questions