Compositional Hierarchies
[ This document was written for WCF Services Version 1 Service Pack 2 and might not be up to date Please see Release Notes or Changelog for a list of changes since WCF RIA Services ]
Open Ria Services enables you to create application logic for data classes that belong to compositional hierarchies that contain classes associated by β€œhas a” relationships in which the containing object (the whole or the parent) controls the creation and lifetime of the contained object (the part or the descendent). For example, the SalesOrderHeader entity has a SalesOrderDetail entity as the details concerning an order only exist as part of the order. For clarify, the composition of classes may be contrasted with the subtyping of classes, which consists of creating a more specific type (a car) by adding details to a more general type (a vehicle). This results in an inheritance hierarchy in which the detailed (derived) class can still be treated as the general (base) type because, to use the example, a car β€œis (still) a” vehicle.
After defining the compositional relationship between the relevant classes, you can perform data modification operations on the entities that treat them as a single unit instead of having to deal with them as separate entities. This simplifies middle-tier logic because you can write application logic for the entire hierarchy instead of having to split that logic to apply to each entity and then attempt to coordinate that split logic during data operations.

Understanding Compositional Hierarchies

In a hierarchy of entities, one entity is referred to as the parent entity and the other related entities are referred to as descendant entities. The parent entity is the class that represents data, which is the single root for the data in the descendant entities. For example, the SalesOrderHeader entity is the parent entity, and SalesOrderDetail is a descendant entity. A single record in the SalesOrderHeader entity can be linked to several records in the SalesOrderDetail entity.
Data classes that are part of a hierarchical relationship typically have the following characteristics:
  • The relationship between the entities can be represented as tree with the descendant entities connected to a single parent entity. The descendant entities can extend for any number of levels.
  • The lifetime of a descendant entity is contained within the lifetime of the parent entity.
  • The descendant entity does not have a meaningful identity outside of the context of the parent entity.
  • Data operations on the entities require that the entities be treated as single unit. For example, adding, deleting, or updating a record in the descendant entity requires a corresponding change in the parent entity.

Defining a Compositional Relationship

You define a compositional relationship between entities by applying the CompositionAttribute attribute to the property that represents the association between entities. The following example shows how to define a compositional relationship between SalesOrderHeader and SalesOrderDetail by using a metadata class. The CompositionAttribute attribute is in the System.ComponentModel.DataAnnotations namespace. You have to reference that namespace by using the using or Imports statement to apply the attribute as shown in the following code.
1
<MetadataTypeAttribute(GetType(SalesOrderHeader.SalesOrderHeaderMetadata))> _
2
Partial Public Class SalesOrderHeader
3
​
4
Friend NotInheritable Class SalesOrderHeaderMetadata
5
​
6
Private Sub New()
7
MyBase.New
8
End Sub
9
​
10
<Include()> _
11
<Composition()> _
12
Public SalesOrderDetails As EntityCollection(Of SalesOrderDetail)
13
​
14
End Class
15
End Class
Copied!
1
[MetadataTypeAttribute(typeof(SalesOrderHeader.SalesOrderHeaderMetadata))]
2
public partial class SalesOrderHeader
3
{
4
internal sealed class SalesOrderHeaderMetadata
5
{
6
private SalesOrderHeaderMetadata()
7
{
8
}
9
​
10
[Include]
11
[Composition]
12
public EntitySet<SalesOrderDetail> SalesOrderDetails;
13
​
14
}
15
}
Copied!
When you apply the CompositionAttribute attribute to a property, the data from the descendant entity is not automatically retrieved with the parent entity. To include the descendent entity in query results, you must apply the IncludeAttribute attribute to the property that represents the descendant entity and include the descendant entity in the query method. The example at the end of the next section shows how to include the descendant entity in the query method.

Domain Service Operations with Compositional Hierarchy

When you define a compositional hierarchy, you must change the way you interact with the parent and descendant entities. The logic you include in domain services must account for the link between the entities. Typically, you define the logic for the hierarchy through domain service methods for the parent entity. In the domain service operations for the parent entity, you process modifications to the parent entity and any modifications to the descendant entities.
The following rules apply to domain service operations for entities with compositional relationships:
  • Query methods for parent or descendant entities are permitted; however, it is recommended that you retrieve descendant entities in the context of the parent entity. An exception is thrown if you modify a descendant entity that has been loaded without the parent entity.
  • Data modification operations can be added to descendant entities, but the permitted operations on a descendant entity are influenced by the permitted operations on the parent entity.
    • If update is permitted on the parent entity, then update, insert, and delete are permitted on the descendant entity.
    • If a parent entity has a named update method, then all descendants must have update enabled.
    • If insert or delete is permitted on the parent entity, then the corresponding operation is permitted recursively on the descendants.
Within the client project, the following rules apply to using entities that have compositional relationships:
  • When a descendant entity contains a change, notification of the change is propagated up to the parent entity. The HasChanges property on the parent entity is set to true.
  • When a parent entity is modified, all of its descendant entities (even those descendants that have not changed) are included in the change set.
  • A public EntitySet in the domain context is not generated on the client for descendant entities. You must access the descendant entity through the parent entity.
  • A descendant entity can be defined with more than one ancestor at the same level, but you must ensure that it is loaded within the context of only a single ancestor.
Data modification operations are executed according to the following rules:
  • An update, insert, or delete operation is executed first on the parent entity before recursively executing any data modification operations on the descendent entities.
  • If the required data operation is not present in a descendant entity, the recursive execution is stopped.
  • When updating a parent entity, the order of execution for data operations on descendants is not specified.
The following example shows the methods for querying, updating, and deleting the SalesOrderHeader entity. The methods include logic to process changes in the descendant entities.
1
<EnableClientAccess()> _
2
Public Class OrderDomainService
3
Inherits LinqToEntitiesDomainService(Of AdventureWorksLT_DataEntities)
4
​
5
Public Function GetSalesOrders() As IQueryable(Of SalesOrderHeader)
6
Return Me.ObjectContext.SalesOrderHeaders.Include("SalesOrderDetails")
7
End Function
8
​
9
Public Sub UpdateSalesOrder(ByVal currentSalesOrderHeader As SalesOrderHeader)
10
Dim originalOrder As SalesOrderHeader = Me.ChangeSet.GetOriginal(currentSalesOrderHeader)
11
​
12
If (currentSalesOrderHeader.EntityState = EntityState.Detached) Then
13
If (IsNothing(originalOrder)) Then
14
Me.ObjectContext.Attach(currentSalesOrderHeader)
15
Else
16
Me.ObjectContext.AttachAsModified(currentSalesOrderHeader, Me.ChangeSet.GetOriginal(currentSalesOrderHeader))
17
End If
18
End If
19
​
20
For Each detail As SalesOrderDetail In Me.ChangeSet.GetAssociatedChanges(currentSalesOrderHeader, Function(o) o.SalesOrderDetails)
21
Dim op As ChangeOperation = Me.ChangeSet.GetChangeOperation(detail)
22
​
23
Select Case op
24
Case ChangeOperation.Insert
25
If ((detail.EntityState = EntityState.Added) _
26
= False) Then
27
If ((detail.EntityState = EntityState.Detached) _
28
= False) Then
29
Me.ObjectContext.ObjectStateManager.ChangeObjectState(detail, EntityState.Added)
30
Else
31
Me.ObjectContext.AddToSalesOrderDetails(detail)
32
End If
33
End If
34
Case ChangeOperation.Update
35
Me.ObjectContext.AttachAsModified(detail, Me.ChangeSet.GetOriginal(detail))
36
Case ChangeOperation.Delete
37
If (detail.EntityState = EntityState.Detached) Then
38
Me.ObjectContext.Attach(detail)
39
End If
40
Me.ObjectContext.DeleteObject(detail)
41
End Select
42
Next
43
End Sub
44
​
45
Public Sub DeleteSalesOrder(ByVal salesOrderHeader As SalesOrderHeader)
46
If (salesOrderHeader.EntityState = EntityState.Detached) Then
47
Me.ObjectContext.Attach(salesOrderHeader)
48
End If
49
​
50
Select Case salesOrderHeader.Status
51
Case 1 ' in process
52
Me.ObjectContext.DeleteObject(salesOrderHeader)
53
Case 2, 3, 4 ' approved, backordered, rejected
54
salesOrderHeader.Status = 6
55
Case 5 ' shipped
56
Throw New ValidationException("The order has been shipped and cannot be deleted.")
57
End Select
58
​
59
End Sub
60
End Class
Copied!
1
[EnableClientAccess()]
2
public class OrderDomainService : LinqToEntitiesDomainService<AdventureWorksLT_DataEntities>
3
{
4
public IQueryable<SalesOrderHeader> GetSalesOrders()
5
{
6
return this.ObjectContext.SalesOrderHeaders.Include("SalesOrderDetails");
7
}
8
​
9
public void UpdateSalesOrder(SalesOrderHeader currentSalesOrderHeader)
10
{
11
SalesOrderHeader originalOrder = this.ChangeSet.GetOriginal(currentSalesOrderHeader);
12
​
13
if ((currentSalesOrderHeader.EntityState == EntityState.Detached))
14
{
15
if (originalOrder != null)
16
{
17
this.ObjectContext.AttachAsModified(currentSalesOrderHeader, this.ChangeSet.GetOriginal(currentSalesOrderHeader));
18
}
19
else
20
{
21
this.ObjectContext.Attach(currentSalesOrderHeader);
22
}
23
}
24
​
25
foreach (SalesOrderDetail detail in this.ChangeSet.GetAssociatedChanges(currentSalesOrderHeader, o => o.SalesOrderDetails))
26
{
27
ChangeOperation op = this.ChangeSet.GetChangeOperation(detail);
28
switch (op)
29
{
30
case ChangeOperation.Insert:
31
if ((detail.EntityState != EntityState.Added))
32
{
33
if ((detail.EntityState != EntityState.Detached))
34
{
35
this.ObjectContext.ObjectStateManager.ChangeObjectState(detail, EntityState.Added);
36
}
37
else
38
{
39
this.ObjectContext.AddToSalesOrderDetails(detail);
40
}
41
}
42
break;
43
case ChangeOperation.Update:
44
this.ObjectContext.AttachAsModified(detail, this.ChangeSet.GetOriginal(detail));
45
break;
46
case ChangeOperation.Delete:
47
if (detail.EntityState == EntityState.Detached)
48
{
49
this.ObjectContext.Attach(detail);
50
}
51
this.ObjectContext.DeleteObject(detail);
52
break;
53
case ChangeOperation.None:
54
break;
55
default:
56
break;
57
}
58
}
59
}
60
​
61
public void DeleteSalesOrder(SalesOrderHeader salesOrderHeader)
62
{
63
if ((salesOrderHeader.EntityState == EntityState.Detached))
64
{
65
this.ObjectContext.Attach(salesOrderHeader);
66
}
67
​
68
switch (salesOrderHeader.Status)
69
{
70
case 1: // in process
71
this.ObjectContext.DeleteObject(salesOrderHeader);
72
break;
73
case 2: // approved
74
case 3: // backordered
75
case 4: // rejected
76
salesOrderHeader.Status = 6;
77
break;
78
case 5: // shipped
79
throw new ValidationException("The order has been shipped and cannot be deleted.");
80
default:
81
break;
82
}
83
​
84
}
85
}
Copied!
Last modified 6mo ago