DSL Tools #12 - Cascade Deleting Domain Classes
NOTE: The procedure described here is based on the domain model described in this previous post.
---
Now for something completely different.
As I said before instances of Entity, NormalAttribute, and Calculated attribute are created at runtime when the user "imports" them from another model. When this happens, the entities are also associated with a ModuleReference domain class which is basically a pointer to the external model used to import those classes (see this post for the domain model part that defines that relation).
Basically, this ModuleReference/Entity relation allows the user to know that he's using model X (ModuleReference X) and that Entity Y is defined on that model. Visually this is shown by a simple connector:
I allow the user to:
- Delete module references.
- Delete entities (meaning that they will not be used in the model).
I don't allow the user to:
- Remove connections between module references and entities. That connection is important to know from where comes a specific entity.
What happens when the user deletes a module reference? The answer is that I need to delete all entities that came from that model (the entities that are connected with the module reference).
This can be achieved when the user "is deleting" the module reference. For that I just need to override OnDeleting in the GraphHasModuleReferences (the embedding relationship that allows the user to place module references in the model) and do the "cascade delete":
1: using System;
2:
3: namespace MyDSL
4: {
5: /// <summary>
6: /// Provides custom behavior for the GraphHasModuleReferences domain class.
7: /// </summary>
8: public partial class GraphHasModuleReferences
9: {
10: #region Public Methods
11:
12: /// <summary>
13: /// Called when an instance of this domain class is being deleted.
14: /// </summary>
15: protected override void OnDeleting()
16: {
17: // Default behavior
18:
19: base.OnDeleting();
20:
21: // If you delete a module reference then all associated entities need to be removed.
22:
23: if ((this.Graph != null) && (!this.Graph.IsDeleting))
24: {
25: // Ask the user
26:
27: string question = string.Format(CommonHelper.Culture, Properties.Resources.RES_ConfirmModuleReferenceDelete, this.ModuleReference.Name);
28: if (CommonHelper.ShowQuestion(question))
29: {
30: // Delete all entities
31:
32: for (int i = this.ModuleReference.Entities.Count - 1; i >= 0; i--)
33: {
34: Entity entity = this.ModuleReference.Entities[i];
35: entity.Delete();
36: }
37: }
38: else
39: {
40: throw new InvalidOperationException(Properties.Resources.RES_UserCanceledOperation);
41: }
42: }
43: }
44:
45: #endregion
46: }
47: }
Simpler that I thought in the first place.
---
NOTE: The procedure described here is based on the domain model described in this previous post.