The wrong place to add this type of business validation rule
is in the UI layer of our application. Adding it in the UI layer of our
application will mean that the rule will be specific to only that one place,
and will not be automatically enforced when we add another page to our
application that also updates Products. Distributing business rules/logic
in our UI layer will also make life extremely painful as our application grows
in size - since changes/updates to our business will necessitate making code
changes all over the place.
The right place to specify this type of business logic
validation is instead in our LINQ to SQL data model classes that we
defined earlier. As I discussed in Part 4 of this series, all classes generated by the LINQ to
SQL designer are defined as "partial" classes - which means that we
can easily add additional methods/events/properties to them. The LINQ to
SQL data model classes automatically call validation methods that we can
implement to enforce custom validation logic within them.
For example, I could add a partial Product class to my
project that implements the OnValidate() partial method that LINQ to SQL calls
prior to persisting a Product entity. Within this OnValidate()
method I could add the following business rule to enforce that products can't
have a Reorder Level if the product is discontinued:
Figure 29
Once I add the above class into my LINQ to SQL
project, the above business rule will be enforced anytime anyone uses my data
model to try and modify the database. This is true for both updating
existing Products, as well as adding new Products into the database.
Because the <asp:LinqDataSource> that we
defined in our pages above works against our LINQ to SQL data model classes,
all of its update/insert/delete logic will now have to pass the above
validation check prior to the change being persisted. We do not need
to-do anything to our UI tier in order for this validation to occur - it will automatically
be applied anywhere and everywhere our LINQ to SQL data model is used.