web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Associating entities via Web API using C#

(1) ShareShare
ReportReport
Posted on by 985

Hi all

I am looking at using the REST endpoints via c#, I am able to create entities by serializing an account object and posting it to the web service endpoint, but I'm having trouble working out how to do so for the single navigation properties. If I was building the JSON manually I'd be able to reference parentaccountid@odata.bind but how do I do so when serializing the object? I can't include a @ or . character in a class property, obviously.

This is what I am currently trying

using (HttpClient httpClient = new HttpClient())
                {
                    // Define the Web API address of the service and the period of time each request has to execute.
                    httpClient.BaseAddress = new Uri(config.ServiceUrl);
                    httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes
                    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                    httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");

                    // Set the type of payload that will be accepted.
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    #region Create a entity
                    // Create an in-memory account using the early-bound Account class.
                    Account account = new Account();
                    account.name = "Contoso";
                    account.telephone1 = "555-5555";
                    account.parentaccountid = "/api/data/v8.1/accounts(B408010B-852B-E611-80DE-C4346BC5C378)";

                    // It is a best practice to refresh the access token before every message request is sent. Doing so
                    // avoids having to check the expiration date/time of the token. This operation is quick.
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken);

                    // Send the request, and then check the response for success.
                    // POST api/data/accounts
                    HttpResponseMessage response =
                        await HttpClientExtensions.SendAsJsonAsync<Account>(httpClient, HttpMethod.Post, "api/data/v8.1/accounts", account);

                    if (response.IsSuccessStatusCode)
                        Console.WriteLine("Account '{0}' created.", account.name);
                    else
                        throw new Exception(String.Format("Failed to create account '{0}', reason is '{1}'.",
                                            account.name, response.ReasonPhrase), new CrmHttpResponseException(response.Content));

But I get this message

A 'PrimitiveValue' node with non-null value was found when trying to read the value of the navigation property 'parentaccountid'; however, a 'StartArray' node, a 'StartObject' node, or a 'PrimitiveValue' node with null value was expected.

Any ideas how I can do this?

*This post is locked for comments

I have the same question (0)
  • Community Member Profile Picture
    on at

    I believe you're simply missing the odata.bind - Payload example for Dynamics 365 online: 

    "parentaccountid@odata.bind": "/contacts(b408010B-852b-e611-80de-c4346bc5c378)";

    Detailed examples for other datatypes are available:

    http://www.inogic.com/blog/2016/02/set-values-of-all-data-types-using-web-api-in-dynamics-crm/

  • Suggested answer
    JohnAnonymous Profile Picture
    5,241 on at

    I have no experience with the C# version of working with REST. But I was thinking two things:

    1. Why don't you use the SDK to connect to CRM and create an account. That seems to be a more logical approach when you are using early bound.

    2. I think you need to change from early bound to late bound to be able to add the @odata.bind.

    I have a scenario where I'm calling the REST endpoint from a C# based application. However I'm not using early bound, so I haven't run into this issue.

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Brad Sprigg ,

    If you are still facing this error. Please do let me know.

    Thanks

    Regards,

    AW

  • Joe Gill Profile Picture
    on at

    I would agree with Martin it seems strange to use Rest Endpoint with early bound objects.

    I tend to use the Newtonsoft json library in this manner 

    JObject newContact = new JObject
    {
    {"lastname", "Gill"},
    {"firstname", "Joe"},
    { "parentcustomerid_account@odata.bind" , "/accounts(alt_key='666')"}
    };

    HttpResponseMessage resp = await httpClient.PostAsync("api/data/v8.0/contacts", new StringContent(newContact.ToString(), Encoding.UTF8, "application/json"));

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans