如何在Dynamics CRM 2015中使用CrmServiceClient设置属性为null
解决Dynamics CRM 2015中CrmServiceClient设置字段为Null的问题
你遇到的空引用异常是因为CrmServiceClient的UpdateEntity方法在处理CrmDataTypeWrapper时,无法正确识别你传入的null值标记方式。针对Dynamics CRM 2015的版本,这里有一个经过验证的可行方案:
// 创建Crm service client对象 CrmServiceClient svc = new CrmServiceClient( new System.Net.NetworkCredential("username", "password", "domain"), "crmhost", "443", "crmorganization", false, true ); // 检查连接是否成功 if (!svc.IsReady) { throw new Exception("Could not connect to CRM Organization.", svc.LastCrmException); } // 创建属性字典 Dictionary<string, CrmDataTypeWrapper> attributes = new Dictionary<string, CrmDataTypeWrapper>(); // ✅ 正确设置日期字段为null的方式 attributes.Add("new_somedatefield", new CrmDataTypeWrapper(null, CrmFieldType.CrmDateTime, true)); // 执行更新操作 svc.UpdateEntity( "new_entityname", "new_entitynameid", (Guid)data[metaData.PrimaryIdAttribute], attributes );
为什么之前的方法无效?
- 直接传入
null作为CrmDataTypeWrapper值:UpdateEntity会尝试访问CrmDataTypeWrapper的内部属性,导致空引用异常。 - 不带
isNull参数的构造函数:即使传入null值,客户端逻辑不会将其标记为“需要设置为null”,反而会判定为未初始化的无效属性。 - 使用可空DateTime变量:同样没有明确告知CRM客户端要执行“置空”操作,只是传递了null值,无法被正确解析。
扩展适配其他字段类型
对于非日期类型的字段,只需要替换对应的CrmFieldType即可:
- 字符串字段置空:
attributes.Add("new_somestringfield", new CrmDataTypeWrapper(null, CrmFieldType.String, true)); - 整数字段置空:
attributes.Add("new_someintfield", new CrmDataTypeWrapper(null, CrmFieldType.Int, true));
额外注意事项
要确保目标字段在CRM实体定义中已经开启“允许空值”,否则即使代码正确,也会触发业务规则异常。
内容的提问来源于stack exchange,提问作者Andy Darby
相关产品推荐
相关产品推荐

