Udostępnij za pośrednictwem


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:

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

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

  1. Open the Northwind.dbml file in the O/R Designer. (Double-click the Northwind.dbml file in Solution Explorer.)

  2. 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.

  3. Place the cursor in the partial Order class.

  4. For Visual Basic projects:

    1. Expand the Method Name list (the combo box that says (Declarations)).

    2. Click OnRequiredDateChanging.

    3. An OnRequiredDateChanging method is added to the partial Order class.

    4. 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:

    1. 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

  1. Press F5.

  2. 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.

  3. 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

  1. Open Form1 in the Code Editor.

  2. Select OrdersDataGridView.

  3. Create an event handler for the DataError event.

  4. 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

  1. Open the Northwind.dbml file in the O/R Designer. (Double-click the Northwind.dbml file in Solution Explorer.)

  2. 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.

  3. Place the cursor in the NorthwindDataset partial class.

  4. For Visual Basic projects:

    1. Expand the Method Name list (the combo box that says (Declarations)).

    2. Click UpdateOrder.

    3. An UpdateOrder method is added to the partial NorthwindDataContext class.

    4. 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:

    1. 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

  1. Press F5.

  2. 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.

  3. Click the Save button on the form.

    At this point validation fails and the exception is thrown.

  4. 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)

Concepts

What's New in Data

LINQ to SQL Queries

Other Resources

Object Relational Designer (O/R Designer)

LINQ to SQL

LINQ to SQL Walkthroughs