views:

308

answers:

3

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.

+1  A: 

Check out this blog post on using transactions in LinqToSql: http://blogs.msdn.com/wriju/archive/2007/08/06/linq-to-sql-using-transaction.aspx

FailBoy
+5  A: 

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.

David Basarab
never noticed the .GetChangeSet() method before! Thanks for that! +1
FailBoy
The actual approach I ended up going with was to create a partial class with the name of the table and implementing validation code in the OnFooChanging() for the fields I wanted to validate. It works to throw exceptions immediately when the value is set rather than at SubmitChanges(). I didn't use the ChangeSet but it pointed me in the right direction and is handy to know anyway.
Nick Gotch
@Nick - I feel useless telling you this because I can't remember the blog where I read about it, but apparently it's a good idea to keep validation seperate from the "OnChange" handlers, because it allows for complex validation scenarios, where the validation of one property depends on the value of others, etc.
Mark
+1  A: 

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. ...
    }
}
BrandonB