I am trying to update a field value of an entity in CRM using C#, but I am not sure how I should do it.
Below are my current code:
var helper = new CRMConnection();
var service = helper.OpenConnection();
var entiyRef = new Entity("financialaid");
string fetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='financialaid'>
<attribute name='financialaidid' />
<attribute name='emailcontent' />
</entity>
</fetch>";
var retrieved = service.RetrieveMultiple(new FetchExpression(fetchXML));
if (retrieved != null && retrieved.Entities.Count > 0){
for (var k = 0; k < retrieved .Entities.Count; i++){
var emailContent = retrieved .Entities[i].GetAttributeValue<string>("emailcontent");
entiyRef["emailcontent"] = "test";
service.Update(entiyRef);
}
}
The code above returned over 5000
records, which I suppose that it is tied to every record I have in CRM. But I am just trying to update a standalone field in the entity.
After which, it hit the following error and exited.
Exception thrown: 'System.ServiceModel.FaultException`1' in Microsoft.Xrm.Sdk.dll
May I know how can I correctly update a field in CRM using FetchXML?
attributeId = 0AB038CE-E57E-EA11-A811-000D3AA3E77C
entityId = b6abe6f6-a876-4a80-87d6-2f1b179d437f
First problem is that you are instantiating the entityRef
as new Entity("financialaid")
but you never assign the Id
property of that object, so the service.Update(entityRef)
call will try to update a record of the financialaid entity that has financialaidid = Guid.Empty
, which should not exist.
The looping of results could be greatly simplified using some Linq expressions or simply a foreach. The looping also does not really make sense, since you are updating the same record every time (the financialaid record with empty id).
If what you are trying to accomplish is to update every record of entity financialaid and set the emailcontent attribute to "test", put this in your loop:
var entityRef = new Entity(retrieved.Entities.LogicalName, retrieved.Entities.Id);
entityRef["emailcontent"] = "test";
service.Update(entityRef);
Note that FetchXML is only a query language, you cannot use FetchXML to update records. Think of it as the select statement of SQL.
Finally, if you just want to bulk update all financialaid records to set the value of a field, I would recommend using an existing tool for that instead of writing a one-off app to do it. In this case the Bulk Data Updater tool in the XrmToolBox would do the job.