6.10. Adding Hooks to Generated Entities
Problem
You have a process to generate your partial class business entity definitions, and you want to add a lightweight notification mechanism.
Solution
Use partial methods to add hooks in the generated code for the business entities.
The process to generate the entities may be from UML, a dataset, or some other object-modeling facility, but when the code is generated as partial classes, add partial method hooks into the templates for the properties that call a ChangingProperty partial method, as shown in the GeneratedEntity class:
public partial class GeneratedEntity
{
public GeneratedEntity(string entityName)
{
this.EntityName = entityName;
}
partial void ChangingProperty(string name, string originalValue, stringnewValue);
public string EntityName { get; private set; }
private string _FirstName;
public string FirstName
{
get { return _FirstName; }
set
{
ChangingProperty("FirstName",_FirstName,value);
_FirstName = value;
}
}
private string _State;
public string State
{
get { return _State; }
set
{
ChangingProperty("State",_State,value);
_State = value;
}
}
}The GeneratedEntity has two properties, FirstName and State. Notice each of these properties has the same boilerplate code that calls the ChangingProperty method with the name of the property, the original, and the new values. If the generated class is used at this point, the ChangingProperty declaration and method will be removed by the compiler, as there is no implementation for ChangingProperty ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access