
Adding Validation for Updates to an Entity Class
In addition to checking values during changes, you can also validate data when an attempt is made to update a complete entity class. Validation during an attempted update enables you to compare values in multiple columns if business rules require this. The following procedure shows how to validate when an attempt is made to update a complete entity class.
Note: |
|---|
Validation code for updates to complete entity classes is executed in the partial
DataContext class (instead of in the partial class of a specific entity class).
|
To validate data during an update to an entity class
Open or create a new LINQ to SQL Classes file (.dbml file) in the O/R Designer. (Double-click the .dbml file in Solution Explorer.)
Right-click an empty area on the O/R Designer and click View Code.
The Code Editor opens with a partial class for the DataContext.
Place the cursor in the partial class for the DataContext.
For Visual Basic projects:
Expand the Method Name list.
Click UpdateENTITYCLASSNAME.
An UpdateENTITYCLASSNAME method is added to the partial class.
Access individual column values by using the instance argument, as shown in the following code:
If (instance.COLUMNNAME = x) And (instance.COLUMNNAME = y) Then
Dim ErrorMessage As String = "Invalid data!"
Throw New Exception(ErrorMessage)
End If
For C# projects:
Because C# projects do not automatically generate the event handlers, you can use IntelliSense to create the partial UpdateCLASSNAME method.
Type partial and then a space to access the list of available partial methods. Click the update method for the class you want to add validation for. The following code resembles code that is generated when you select an UpdateCLASSNAME partial method:
partial void UpdateCLASSNAME(CLASSNAME instance)
{
if ((instance.COLUMNNAME == x) && (instance.COLUMNNAME = y))
{
string ErrorMessage = "Invalid data!";
throw new System.Exception(ErrorMessage);
}
}