How to use CrmServiceClient to set a null attribut

2019-02-25 18:23发布

问题:

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:

This should work.

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