How to update multiple associated records using D365 plugin code?
Here in this scenario, I have a custom entity called "Sample" and it's having a 1:N relationship with a Case entity. Now I want to update few fields on the "Sample" record and it should automatically update few fields on the Case record once click on the save record.
Let's proceed...
1. Get the Sample record Id first which can be passed to fetch XML conditions to update the only related record to this ID.
2. Follow the code below, fetch the case record using advance find, convert it to C# format and add it variable as shown
-> Pass the formated fetch XML to service.retrieveMultiople to fetch the record collection
-> Add it to an entity collection and read and update records one by one
-> Call the service.update with entity object in it.
Entity esample;
DateTime createdon = esample.GetAttributeValue<DateTime>(Sample.Createdon);//"createdon"DateTime modifiedon = esample.GetAttributeValue<DateTime>(Sample.Modifiedon);//"modifiedon"
try
{
var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='incident'>
<attribute name='incidentid' />
<attribute name='createdon' />
<attribute name='modifiedon' />
<order attribute='createdon' descending='false' />
<filter type='and'>
<condition attribute='new_sampleid' operator='eq' value='{0}' />
</filter>
</entity>
</fetch>";
fetchXml = string.Format(fetchXml, esample.Id);//Pass sample record id index
caseResult = service.RetrieveMultiple(new FetchExpression(fetchXml));
if (caseResult != null && caseResult.Entities.Count > 0)
{
foreach (var caseRecord in caseResult.Entities)
{
Entity eCase = new Entity(Cases.EntityLogicalName);//"incident" entity logical name
eCase.Id = caseRecord.Id;
eCase[Cases.CreatedonDatetime] = createdon;//eCase["createdon"]
eCase[Cases.ModifiedonDatetime] = modifiedon;//eCase["modifiedon"]
service.Update(eCase);
}
}
}
The record gets updated go and verifies the associated record.
Thats' all
Keep CRMing...