Back to Devexpress

Custom Collection Types

xpo-3266-query-and-shape-data-custom-collection-types.md

latest2.7 KB
Original Source

Custom Collection Types

  • Sep 15, 2020
  • 2 minutes to read

Sometimes it is necessary to derive custom collection types from the standard XPCollection or the XPCollection<T>. The standard types have a special constructor that is used when they must be initialized as relationship collections. This specific collection constructor is relevant in two ways:

  • Be sure that your derived collection type implements it.
  • In relation properties on the “one” side of a one-to-many relationship, or in the properties on both sides of a many-to-many relationship, you must use this constructor to create the collection of your derived type.

So, assuming you had a derived collection class MyCollection<T>:

csharp
public class MyCollection<T> : XPCollection<T> {
// ...
public MyCollection(Session session, object theOwner, XPMemberInfo refProperty) :
 base(session, theOwner, refProperty) { }
// ...
}
vb
Public Class MyCollection(Of T)
    Inherits XPCollection(Of T)
' ...
Public Sub New(ByVal session As Session, ByVal theOwner As Object, ByVal refProperty As XPMemberInfo)
    MyBase.New(session, theOwner, refProperty)
End Sub
' ...
End Class

To use this collection type in a relation property, use the following code:

csharp
public class Album : XPObject {
    // ...
}

public class Artist : XPObject {
    // ...
    MyCollection<Album> myCollection;
    [Association("Artist-Albums")]
    public MyCollection<Album> Albums {
        get {
            if (myCollection == null)
                myCollection = new MyCollection<Album>(Session, this,
                    ClassInfo.GetMember(nameof(Albums)));
            return myCollection;
        }
    } 
    // ...
}
vb
Public Class Album
    Inherits XPObject
    ' ...
End Class

Public Class Artist
    Inherits XPObject
    ' ...
    Private myCollection As MyCollection(Of Album)
    <Association("Artist-Albums")> _
    Public ReadOnly Property Albums() As MyCollection(Of Album)
        Get
            If myCollection Is Nothing Then
                myCollection = New MyCollection(Of Album)(Session, Me, ClassInfo.GetMember(NameOf(Albums)))
        End If
            Return myCollection
        End Get
    End Property
    ' ...
End Class

The code in the property getter is identical to that in the GetCollection<T> method - but because that method doesn’t return our own collection type, we have to replace it.

See Also

XPO Templates