Description:
Is it possible to write a function that is able to return a list of strings that contain the structure of a persistent object? This could be used for a generic XPO search system where the user can select from a list which properties to search for and I could translate this into XPO criteria.
Answer:
You should use the ClassInfo property of a persistent object and iterate through the PersistentProperties and CollectionProperties lists. Here is the necessary code:
C#using DevExpress.Xpo;
using DevExpress.Xpo.Metadata;
using DevExpress.Xpo.Metadata.Helpers;
string[] GetObjectProperties(Type objectType) {
XPClassInfo classInfo = Session.DefaultSession.Dictionary.GetClassInfo(objectType);
if(classInfo != null)
return GetObjectProperties(classInfo, new ArrayList());
return new string[] {};
}
string[] GetObjectProperties(XPClassInfo xpoInfo, ArrayList processed) {
if(processed.Contains(xpoInfo)) return new string[] {};
processed.Add(xpoInfo);
ArrayList result = new ArrayList();
foreach(XPMemberInfo m in xpoInfo.PersistentProperties)
if(!(m is ServiceField) && m.IsPersistent) {
result.Add(m.Name);
if(m.ReferenceType != null) {
string[] childProps = GetObjectProperties(m.ReferenceType, processed);
foreach(string child in childProps)
result.Add(string.Format("{0}.{1}", m.Name, child));
}
}
foreach(XPMemberInfo m in xpoInfo.CollectionProperties) {
string[] childProps = GetObjectProperties(m.CollectionElementType, processed);
foreach(string child in childProps)
result.Add(string.Format("{0}.{1}", m.Name, child));
}
return result.ToArray(typeof(string)) as string[];
}
See Also:
How to clone a persistent object
How to access the property of a class by its name in C#
I want to get the similar behavior but this seems to be 8 year old post. Do you have a new way of doing same thing?
This example is still actual. There is no better way to accomplish this task.
Hello, can you update this example or give a link to another post, please? I tried to use it, but got an exception (associated with using DefaultSession).
You may get an exception if you try to use the Session.DefaultSession property in XAF, or if the XpoDefault.Session property is not initialized in your application. In these cases, obtain an appropriate Session instance based on your application's specifics. For example, in XAF, you can get it using the XPObjectSpace.Session property, or using the Session property of any persistent object. In WinForms applications, use the Form's Session or create a new Session using the application's Data Access Layer. Refer to the Session topic for additional information.