'How to read entity object in C#
Whenever I try to get a specific value from an object my editor throws the error: 'Object does not contain method for {variable name}'. Here is my code so far:
EntityCollection accounts = service.RetrieveMultiple(new FetchExpression(fetchXml));
foreach (var c in accounts.Entities)
{
var workOrderNum = c.GetAttributeValue<AliasedValue>("wo_workOrderNumber");
var workOrderCustomer = c.GetAttributeValue<AliasedValue>("wo_customer");
# This line succeeds
Console.WriteLine("Name: {0}", workOrderNum != null ? (string)workOrderNum.Value : "");
# This line fails because 'Object does not contain a definition for name'
Console.WriteLine("Name: {0}", workOrderCustomer != null ? (string)workOrderCustomer.Value.Name : "");
}
When I debugged the code I saw that the variable workOrderCustomer has a name variable within it:
workOrderCustomer Entity Object.png
Instead of doing workOrderCustomer.Value.Name i've tried workOrderCustomer.Value['Name'], workOrderCustomer.Value.['Name'] as well as a few other combinations to no avail. Any idea on how I can get the name variable from the workOrderCustomer object?
Appreciate the help!
Solution 1:[1]
I solved the issue. I had to cast the object inside the 'AliasedValue' object with the correct object name that allowed me to pull the name variable. In this case it looks like an object 'EntityReference' was inside the 'AliasedValue' object. Here's the line of code that ended up working for me:
#'(AliasedValue)c["wo_customer"]).Value' gets the EntityReference Object
var Name = ((EntityReference)((AliasedValue)c["wo_customer"]).Value).Name;
Solution 2:[2]
a dumb fix would be to simply create a method that return the name in workOrderCustomer and simply call that method in your console writeline
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JH 902 |
| Solution 2 | Math_Guerin |
