2
votes

I am struggling using the CrmServiceClient to update attribute values to null.

My code is working fine for non null values but fails with an exception:

Object reference not set to an instance of an object. at Microsoft.Xrm.Tooling.Connector.CrmServiceClient.AddValueToPropertyList(KeyValuePair2 Field, AttributeCollection PropertyList) at Microsoft.Xrm.Tooling.Connector.CrmServiceClient.UpdateEntity(String entityName, String keyFieldName, Guid id, Dictionary2 fieldList, String applyToSolution, Boolean enabledDuplicateDetection, Guid batchId)

whenever I try to set a null value.

So far I have tried the following:

// create Crm service client object
CrmServiceClient svc = new CrmServiceClient(
new System.Net.NetworkCredential("username", "password", "domain"),
                "crmhost",
                "443",
                "crmorganization",
                false,
                true
                );

// check the connection to CRM was successful
if (!svc.IsReady)
{
    throw new Exception("Could not connect to CRM Organization.", svc.LastCrmException);
}

// create a Dictionary to store the attributes to be added to the entity
Dictionary<string, CrmDataTypeWrapper> attributes = new Dictionary<string, CrmDataTypeWrapper>();

//this doesn't work
attributes.Add("new_somedatefield", null);

// and this doesn't work
attributes.Add("new_somedatefield", new CrmDataTypeWrapper(null, CrmFieldType.CrmDateTime));

// this also doesn't work
DateTime? nullDate = new DateTime();
nullDate = null;
attributes.Add("new_somedatefield", new CrmDataTypeWrapper(nullDate, CrmFieldType.CrmDateTime));

svc.UpdateEntity("new_entityname", "new_entitynameid", (Guid)data[metaData.PrimaryIdAttribute], attributes));

There's nothing specifically mentioned in the documentation about setting null values.

Has anybody successfully managed to achieve this?

EDIT - To clarify I need to target Dynamics CRM 2015, the Update method on the CrmServiceClient is not available until 2016.

1
Why can't you use latest Xrm.Tooling? It can call CRM 2015 successfully, there is no reason for using outdated libs outside pluginsPawel Gradecki
Yes, this seems to have worked. Using the suggestion from @Arun I can now successfully set null values. I assumed I'd need to use the Xrm.Tooling matching our version of CRM. I'll run some more tests and scenarios before putting this into production. Still begs the question how it was supposed to be achieved with the version I was using though!Andy Darby

1 Answers

1
votes

This should work.

Entity ent = new Entity("entityname");
ent.Attributes["datefieldname"] = null;
ent.id = Id;
service.Update(ent);