Description:
I have a rather complex query, which returns an array of object key values. The query cannot be represented with a CriteriaOperator because it contains some complex formulas. Is there a way to load the objects by these IDs into an XPCollection for viewing and processing?
Answer:
Since version 6.2 you can utilize the XPCursor class for this task. Below is some sample code. Please note that the XPCollection is created with the LoadingEnabled property set to False (the last parameter in the constructor).
C#object[] idList = new object[] { 1, 2, 3 };
Type objType = typeof(PersistentObject1);
Session session = XpoDefault.Session;
XPCursor cursor = new XPCursor(session, objType, idList);
XPCollection col = new XPCollection(session, objType, false);
col.AddRange(cursor);
With XPO 1.x and 6.1.x please use the GetObjects function listed below to create a collection of objects by their identifiers:
C#using DevExpress.Xpo;
XPCollection GetObjects(Session session, Type persistentType, object[] identifiers) {
CustomXPCollection result = new CustomXPCollection(session, persistentType);
result.identifiers = identifiers;
return result;
}
public class CustomXPCollection : XPCollection {
public CustomXPCollection(System.Type objType): base(objType) {}
public CustomXPCollection(Session session, System.Type objType): base(session, objType) {}
public object[] identifiers;
protected override void LoadContent() {
if(identifiers == null || ObjectClassInfo == null) return;
const int BunchCount = 256;
int index = 0;
while(index < identifiers.Length) {
int bunch = Math.Min(identifiers.Length - index, BunchCount);
object[] bunchOids = new object[bunch];
Array.Copy(identifiers, index, bunchOids, 0, bunch);
CriteriaOperator criteria = new InOperator(ObjectClassInfo.KeyProperty.Name, identifiers);
ICollection objects = Session.GetObjects(ObjectClassInfo, criteria, null, null, false);
foreach(IXPSimpleObject obj in objects)
InternalAddObject(obj);
index += bunch;
}
}
public override void Reload() {}
}
See Also:
How to construct complex queries
What is the best way to obtain a collection of persistent objects for processing?
How to create an empty XPCollection of a specified type