Let's consider a simple example of a One-to-One relationship, when both classes that participate in the relationship have properties with a reference to the instance of their opposite class. It's necessary to write extra code within the property's setter method for each class that participates in the relationship to ensure the relationship's integrity, i.e. when a new object is assigned to a reference property, the reference to the previous object instance should be cleared and the assigned object should reference the current one.
This technique can be implemented as shown in the following code example.
1: ' Represents the Building class which refers to the building's owner.
2: Public Class Building : Inherits XPObject
3: Dim _owner As Person = Nothing
4: Public Property Owner() As Person
5: Get
6: Return _owner
7: End Get
8: Set(ByVal Value As Person)
9: If _owner Is Value Then
10: Return
11: End If
12:
13: ' Store a reference to the former owner.
14: Dim prevOwner As Person = _owner
15: _owner = Value
16:
17: If IsLoading Then Return
18:
19: ' Remove an owner's reference to this building, if exists.
20: If Not (prevOwner Is Nothing) AndAlso prevOwner.House Is Me Then
21: prevOwner.House = Nothing
22: End If
23:
24: ' Specify that the building is a new owner's house.
25: If Not (_owner Is Nothing) Then
26: _owner.House = Me
27: End If
28:
29: OnChanged("Owner")
30:
31: End Set
32: End Property
33: End Class
34:
35: ' Represents the Person class which refers to the person's house.
36: Public Class Person : Inherits XPObject
37: Dim _house As Building = Nothing
38: Public Property House() As Building
39: Get
40: Return _house
41: End Get
42: Set(ByVal Value As Building)
43: If _house Is Value Then
44: Return
45: End If
46:
47: ' Store a reference to the person's former house.
48: Dim prevHouse As Building = _house
49: _house = Value
50:
51: If IsLoading Then Return
52:
53: ' Remove a reference to the house's owner, if the person is its owner.
54: If Not (prevHouse Is Nothing) AndAlso prevHouse.Owner Is Me Then
55: prevHouse.Owner = Nothing
56: End If
57:
58: ' Specify the person as a new owner of the house.
59: If Not (_house Is Nothing) Then
60: _house.Owner = Me
61: End If
62:
63: OnChanged("House")
64: End Set
65: End Property
66: End Class
[eXpressApp Framework]
No comments:
Post a Comment