Walkthrough: Adding Validation to Entity Classes
Validating data is the process of confirming that the values entered into data objects comply with the constraints in an object's schema, in addition to the rules established for your application. Validating data before you send updates to the underlying database is a good practice that reduces errors and the potential number of round trips between an application and the database.
The Object Relational Designer (O/R Designer) provides partial methods that enable users to extend the designer-generated code that runs during Inserts, Updates, and Deletes of complete entities, and also during and after individual column changes.
This walkthrough provides step-by-step instructions for adding validation to LINQ to SQL entity classes and expands upon the Walkthrough: Creating LINQ to SQL Classes (O/R Designer) topic.
In this walkthrough, you will learn how to perform the following tasks:
Add validation for changes to the data in a specific column.
Add validation for updates to a complete entity.
Prerequisites
To complete this walkthrough, you need the following:
The project created in Walkthrough: Creating LINQ to SQL Classes (O/R Designer).
Access to the Northwind sample database. For more information, see How to: Install Sample Databases.
Note
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.
Opening the ORDesignerWalkthrough Solution
To open the ORDesignerWalkthrough solution
On the File menu, point to Open, click Project/Solution, and then navigate to the location of the ORDesignerWalkthrough.sln file.
Note
The ORDesignerWalkthrough.sln file is created in the Walkthrough: Creating LINQ to SQL Classes (O/R Designer) topic and is a prerequisite to completing this walkthrough. Complete the Walkthrough: Creating LINQ to SQL Classes (O/R Designer) topic, saving the solution when you are finished, if you have not yet done this.
Adding Validation for Changes to the Value in a Specific Column
In this part of the walkthrough, you will add validation logic to the RequiredDate column of an order. You will add code to verify that the RequiredDate is earlier than the current day. Because the validation is performed in the actual class definition (instead of in the user interface) an exception is thrown if the value fails validation.
To validate data during a column's value change
Open the Northwind.dbml file in the O/R Designer. (Double-click the Northwind.dbml file in Solution Explorer.)
Because you are adding validation to the RequiredDate of an order, right-click the Order class in the designer and click View Code.
The Code Editor opens with a partial class for the order.
Place the cursor in the partial Order class.
For Visual Basic projects:
Expand the Method Name list (the combo box that says (Declarations)).
Click OnRequiredDateChanging.
An OnRequiredDateChanging method is added to the partial Order class.
Add the following code inside the OnRequiredDataChanging method to ensure that the value entered for the RequiredDate is not earlier than the current date:
If value.HasValue Then If value < Today Then Throw New Exception("Required Date cannot be in the past") End If End If
For C# projects:
Add the following code to the partial Order class to ensure that the value entered for the RequiredDate is not earlier than the current date:
partial void OnRequiredDateChanging(System.DateTime? value) { if (value < System.DateTime.Today) { throw new System.Exception("Required Date cannot be in the past"); } }
Testing the Application
Testing the validation logic requires running the application and entering values that will cause validation to fail.
To test the application
Press F5.
In the grid that displays the orders, change the RequiredDate of an order to a date before the current date and navigate off the record to accept the change.
The new value causes validation to fail, and the exception is thrown as expected.
Close the form. (Stop debugging.)
Handling the Validation Error in the DataGridView
Testing the application resulted in an error message from the DataGridView that instructs developers to handle the DataError event. The following procedure shows how to handle this event.
To handle the validation error in the DataGridView
Open Form1 in the Code Editor.
Select OrdersDataGridView.
Create an event handler for the DataError event.
Add code to display the error. The event handler looks like the following:
Private Sub OrdersDataGridView_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles OrdersDataGridView.DataError MessageBox.Show(e.Exception.Message) End Sub
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e) { MessageBox.Show(e.Exception.Message); }
Adding Validation for Updates to an Entity Class
In addition to checking values during changes, you can validate data when an attempt is made to update a complete entity class. Validation during an attempted update enables comparing values in multiple columns if business rules require this. For example, the following procedure shows how to validate that the correct shipping company is used if the freight charge is less than a set limit.
To validate data during an update to an entity class
Open the Northwind.dbml file in the O/R Designer. (Double-click the Northwind.dbml file in Solution Explorer.)
Because you are adding validation to the update of a complete Order class, the partial methods that you have to access are located in the generated DataContext class (NorthwindDataContext). Right-click an empty area in the O/R Designer and click View Code.
The Code Editor opens in the partial class for the NorthwindDataContext.
Place the cursor in the NorthwindDataset partial class.
For Visual Basic projects:
Expand the Method Name list (the combo box that says (Declarations)).
Click UpdateOrder.
An UpdateOrder method is added to the partial NorthwindDataContext class.
Federal Shipping does not deliver if the Freight value is less than 10. Therefore, add the following code inside the UpdateOrder method to ensure that the value entered for ShipVia is not Federal Shipping if the Freight value is less than 10:
If (instance.ShipVia = 3) And (instance.Freight < 10) Then Dim ErrorMessage As String = "Federal Shipping " & _ "does not deliver for less than 10. " & _ "You must use a different shipper." Throw New Exception(ErrorMessage) End If
For C# projects:
Add the following code to the partial NorthwindDataContext class to ensure that the value entered for ShipVia is not Federal Shipping if the Freight value is less than 10:
partial void UpdateOrder(Order instance) { if ((instance.ShipVia == 3) && (instance.Freight < 10)) { string ErrorMessage = "Federal Shipping " + "does not deliver for less than 10. " + "You must use a different shipper."; throw new System.Exception(ErrorMessage); } }
Testing the Application
To test the validation logic, run the application and enter values that will cause validation to fail.
To test the application
Press F5.
In the grid that displays the orders, locate a record for which ShipVia is 3. Change the Freight to 5 and navigate off the record to accept the change.
Because validation is not performed until the record is actually submitted for update, validation does not yet fail.
Click the Save button on the form.
At this point validation fails and the exception is thrown.
Close the form. (Stop debugging.)
Next Steps
Depending on your application requirements, there are several steps that you may want to perform after you add validation to LINQ to SQL entity classes. You could make the following enhancement to this application:
- Create more LINQ queries to sort and filter the data. For information, see LINQ to SQL Queries.
See Also
Tasks
Walkthrough: Creating LINQ to SQL Classes (O/R Designer)