Getting and Setting Fields Through Metadata
Getting Field Values
To obtain the value of a field on a particular entity instance, call the FieldInfo.GetValue method:
Getting the value of a field on an entity instance |
var referenceField = classInfo.Fields.First(f => f.PropertyName == "OrderReference"); |
GetValue accepts any entity, but throws an exception if the entity is not of the type on which the FieldInfo is defined. This can be an issue when inheritance is in play: if you are processing entities from across the inheritance hierarchy, then you will probably be using a flattened collection to ensure you process all fields, but a particular entity instance won’t have the fields declared in sibling or derived classes. To check if the FieldInfo is defined on the entity, call IsDefined:
Using IsDefined to check that it is safe to get a field value |
var classInfo = EntityInfo.FromType(typeof(SalesItem)); |
FieldInfo also provides a TryGetValue method which combines the check with the retrieval, but using IsDefined and GetValue is usually more convenient if you want to cast the value to a particular type.
From LightSpeed 5 onwards, FieldInfo includes extra information on properties:
· Validations (which returns a list of the validations defined on entities of its type)
· IsNullable
· IsIdentityField
Getting Association Values
When you use FieldInfo.GetValue to retrieve an association value, this causes LightSpeed to load the association if it not already loaded. For to-one associations, the return value is the associated entity, not the EntityHolder which implements the association.
Setting Field Values
Conversely, you can set the value of a field on an entity instance using SetValue:
Setting the value of a field on an entity instance |
var referenceField = classInfo.Fields.First(f => f.PropertyName == "OrderReference"); |
As with GetValue, you can use IsDefined to check that the field exists on the entity instance at hand, or TrySetValue to combine the check with the set.
When you call FieldInfo.SetValue, you are directly setting the underlying CLR field. (Remember, the LightSpeed metamodel represents fields, not properties.) The property setter is not called. If you have custom logic in the property setter, for example to validate or transform input values, FieldInfo.SetValue bypasses that custom logic.