[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:

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/create-entity-web-api

{

“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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s