Custom Collection Types
- 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>
:
public class MyCollection<T> : XPCollection<T> {
// ...
public MyCollection(Session session, object theOwner, XPMemberInfo refProperty) :
base(session, theOwner, refProperty) { }
// ...
}
To use this collection type in a relation property, use the following code:
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;
}
}
// ...
}
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