Update the email address for the primary contact of the account in Dynamic CRM 365
var account = new Entity("account");
account.Id = retrievedAccount.Id;
//Define relationships
var primaryContactRelationship = new Relationship("account_primary_contact");
var AccountTasksRelationship = new Relationship("Account_Tasks");
//Update the account name
account["name"] = "New Account name";
//Update the email address for the primary contact of the account
var contact = new Entity("contact");
contact.Id = retrievedAccount.RelatedEntities[primaryContactRelationship]
.Entities.FirstOrDefault().Id;
contact["emailaddress1"] = "[email protected]";
List<Entity> primaryContacts = new List<Entity>();
primaryContacts.Add(contact);
account.RelatedEntities.Add(primaryContactRelationship, new EntityCollection(primaryContacts));
// Find related Tasks that need to be updated
List<Entity> tasksToUpdate = retrievedAccount
.RelatedEntities[AccountTasksRelationship].Entities
.Where(t => t["subject"].Equals("Example Task")).ToList();
// A list to put the updated tasks
List<Entity> updatedTasks = new List<Entity>();
//Fill the list of updated tasks based on the tasks that need to but updated
tasksToUpdate.ForEach(t => {
var updatedTask = new Entity("task");
updatedTask.Id = t.Id;
updatedTask["subject"] = "Updated Subject";
updatedTasks.Add(updatedTask);
});
//Set the updated tasks to the collection
account.RelatedEntities.Add(AccountTasksRelationship, new EntityCollection(updatedTasks));
//Update the account and related contact and tasks
svc.Update(account);