0

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?

Myster
  • 17,704
  • 13
  • 64
  • 93
  • A query to the database must match the database language. The resutls of the database query need to be put into you class Foo_module so your controller will work with the database. So the server code queries the database and creates a Foo_module that is send in a Post. Then client will get the response in proper format. – jdweng May 13 '21 at 07:17
  • I am writing the client only, the server is Micosoft Dynamics 365, I'll add that tag – Myster May 16 '21 at 21:26

1 Answers1

0

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);
Myster
  • 17,704
  • 13
  • 64
  • 93