Tutorial 10: Add custom business logic

Description Article
Table of Contents
Summary

Linq To SQL permits to add custom logic, auditing or logging to each entiity:

  • validation of global custom rules added to an entity before persisiting it’s values to the database;
  • specific custom logic before each of the specific CUD operations for an entiity; and
  • specific custom logic when each property value of an entitiy changes.
Operations
Custom Property Validation Support

To add custom validation rules for each entitiy property the following steps must be considered:
1) Implement the partial method “On[PropertyName]Changing()” on the partial entity class. This method will be invoked when the property value changes.

How to do it
public partial class Customer {

   partial void OnPhoneChanging(string value) {

      // TODO: add custom logic...

   }

}
Custom Entity Object Validation Support

To add custom entity level validation rules the following steps must be considered:
1) Implement the partial method “OnValidate()” on the partial entity class. This method that will be invoked before to the entity’s values being persisted into the database.

How to do it
public partial class Customer {

   partial void OnValidate() {

	  // TODO: add custom logic...
   }
}
Custom Entity Insert/Update/Delete Method Validation (CUD operations)

To add validation logic that is specific to insert, update or delete scenarios the following steps must be considered:
1) Add a partial class to extend the base DataContext class;
2) Implement partial methods to customize the Insert, Update and Delete logic for the data model entities. These methods are named [Action][Entity] and will be called automatically when the DataContext::SubmitChanges() method is invoked

How to do it
partial class TrainingDataContext {

   partial void InsertCustomer(Customer pinstance) {

      // TODO: add custom logic...
      ExecuteDynamicInsert(instance);
   }

   partial void UpdateCustomer(Customer instance) {

      // TODO: add custom logic...
      ExecuteDynamicUpdate(instance);
   }

   partial void DeleteCustomer(Customer instance) {

      // TODO: add custom logic...
      ExecuteDynamicDelete(instance);
   }
}