Recently, I was trying to retrieve formatted values using Linq.I was able to do for the attribute of the same entity with the help of this blog: Read Formatted Values using Linq.
However, when I tried to do for the related entity had to modify the code and get the desired values.
Suppose I want to retrieve Contact along with Account and a formatted value of Preferred Contact Method field of Account then I had to use the below code snippet:
var data = from c in svcContext.CreateQuery(“contact”)
join acc in svcContext.CreateQuery(“account”)
on c[“contactid”] equals acc[“primarycontactid“]
select new
{
contact_name = c[“fullname”],
account_name = acc[“name”],
accountPrefferedCodeValue = acc.Attributes.Contains(“preferredcontactmethodcode”) ? acc[“preferredcontactmethodcode”]: “No Val“,
accountpreferredCode = c.FormattedValues.Contains(“acc_0.preferredcontactmethodcode”) ? c.FormattedValues[“acc_0.preferredcontactmethodcode”] : “”
};
where svcContext is object of OrganizationServiceContext.
So as you can see here we are trying to retrieve related preferredcontactmethodcode value of the joined Account entity.
So while reading the OptionsetValue in extra value field we use the “acc” i.e. Account object and while reading the Formatted Value we use “c” i.e. variable for representing Contact object.
Also as it is the first join in the Linq query for the attribute name we need to add “acc”+ “_0.” + “preferredcontactmethodcode”
So if we have multiple joins then you need to increment the count from 0 to 1 & so on along with the linked entity variable + linked attribute name.
Hope this saves your time and help you with LINQ queries in CRM.
