Search code examples
c#dynamics-crmodatamicrosoft-odata

How do I get Microsoft.OData.Client to Associate tables on update?


I have tested this request (to Microsoft Dynamics 365 CRM) in postman and it works correctly:

POST request to https://example.com/api/data/v9.2/foo_module?$select=foo_moduleid 

Headers include:

Prefer:return=representation

Body

{
    foo_AccountId@odata.bind : "/accounts(b770a30d-55d9-e211-89ad-005056ae0100)",
    "foo_name": "Module Name"
}

I have no idea how to get the Microsoft.OData.Client to generate this request. Updating the record would look like the following, and this does work as I can use the primary key

var moduleQuery = from x in context.foo_modules
                    where x.foo_moduleid == record.CrmId
                    select x;

module = new DataServiceCollection<Foo_module>(moduleQuery).Single();
module.Foo_name = $"Example Online Module (from c# at {DateTime.Now})";

var response = context.SaveChanges(SaveChangesOptions.PostOnlySetProperties);

Summary How do I get the foo_AccountId@odata.bind : "/accounts(b770a30d-55d9-e211-89ad-005056ae0100)" property in the body when using Microsoft.OData.Client?


Solution

  • The solution was to query the associated record (account) and assign it to the appropriate property.
    Here's the code:

    var context = _dynamicsContextFactory.CreateContext();
    
    var accountQuery = context.Accounts.Where(x =>
                        x.Primarycontactid.Lastname == lastname
                        && x.Accountnumber == number
                    );
    var account = new DataServiceCollection<Account>(accountQuery).Single();
    var collection = new DataServiceCollection<Foo_module>(context);
    var module = new Foo_module();
    module.Foo_AccountId = account; // <--- this is the important line
    collection.Add(module);
    module.Foo_name = $"Example Online Module (from c# at {DateTime.Now})";
    var response = context.SaveChanges(SaveChangesOptions.PostOnlySetProperties);