How to get a property by it's name


Is there a way to get (or set) a property value while giving it's name. A thing similar to Dataset.FieldByName(afieldname).Value ?

I guess this could be done with RTTI but how does Tnullable<> properties kind behave ?

Thank you


Yes you can do it via RTTI. Nullable<T> is a record so you should handle it property. However there are helper methods in TMappingExplorer for that as well. One example:

  Value := Manager.Explorer.GetMemberValue(Object, RttiInfo);
  Manager.Explorer.SetMemberValue(Object, RttiInfo, Value);

The above will take care of Nullable and Proxy types transparently. To get RttiInfo you can use this:

  Info := Manager.Explorer.GetOptimization(TMyEntity, 'PropName');
  // You should later destroy Info object!


  // For primitive types:
  Info := Manager.Explorer.GetColumnByPropertyName(TMyEntity, 'PropName').Optimization;
  // For instance (association) types:
  Info := Manager.Explorer.GetAssociationByPropertyName(TMyEntity, 'AssocPropName').Optimization;

  // No need to destroy Info objects in this case

Wagner R. Landgraf2018-03-02 15:06:43

Thank you Landgraf.

Thing is that I'm trying to write values from an Excel file (using the great FlexCell library).
I have looked at your exemple and adapted my code this way (PropName is fetched from a text file) :

        MyObject:= TMyObject.Create;
        Info := Manager.Explorer.GetColumnByPropertyName(TMyObject,FieldsName).Optimization;

        varval := FormatValue( xlsIn.GetCellValue(x,y)) ; //reading a Cell from Flexcell and getting a variant value
        value := TValue.From(varval);
        Manager.Explorer.SetMemberValue(Contracts_MGAM, Info, value);

This code ends with a $C0000005 exception at address 0000000 ! Did I miss something ?

Hi, the code I provided is a direct, compact code. But I suggest you break it into pieces and check each step, especially because you are trying it for the first time.

In which line you get that error? 
Have you checked if GetColumnByPropertyName is returning an object? 
Is Manager created? 
Is Info not nil?
Why are you creating MyObject instance if later to set property you are using Contracts_MGAM?
Is Contracts_MGAM not nil?

Wagner R. Landgraf2018-03-05 20:37:16

Hi Landgraf,

It was my fault. It was a typo in my code, I used the wrong object...

Thank you