[Small Tips] EntityReferences when using ExpandoObjects to create records through the Web API
Lately, I have been playing a lot with the Dynamics 365 Web API, rather than using HTTP Request directly I decided to try David Yack’s library which so far is working great!
https://github.com/davidyack/Xrm.Tools.CRMWebAPI/tree/master/dotnet
Because I was using Azure Functions v2 I couldn’t use the Dynamics 365 Core Assemblies so I had to improvise a little bit when creating records.
Strings are of course fine, Statuses and Option sets you can use the numeric value and it will work, but what about Lookups?
If we check the SDK we can see that the request should follow this format:
{
“name”:”Sample Account”,
“primarycontactid@odata.bind”:”/contacts(00000000-0000-0000-0000-000000000001)”
}
What about when we are using ExpandoObjects like in David’s library? Well, just cast it to a Dictionary and send that instead 
dynamic account = new ExpandoObject(); //We won’t be using this one anymore.
var accountDict = (IDictionary)account;
accountDict.Add("primarycontactid@odata.bind", "contacts(54210106-dbeb-e711-a952-000d3a296acd)");
accountDict.Add("name ", “Sample Account”);
Guid createdAccount = await api.Create("accounts",accountDict);
Hope it helps!
Mario
This was originally posted here.

Like
Report
*This post is locked for comments