使用QueryByAttribute无法检索空值 [英] Using QueryByAttribute cannot retrieve null values
问题描述
我是CRM开发的新手。除了我在C#应用程序中CRM 2011中的现有值之外,我还想更新自定义字段值。如果该字段具有某些值,则工作正常,但如果为null,则我收到字典中不存在给定的键。错误。
I am new to CRM Development. I would like to update the custom field values in addtion to its existing values in the CRM 2011 from my C# application. If the field has some values then it is working fine, but if it null then i am receiving "The given key was not present in the dictionary." error.
以下代码是我要实现的目标。
The code below is what i am trying to achieve.
IOrganizationService service = (IOrganizationService)serviceProxy;
QueryByAttribute querybyattribute = new QueryByAttribute("salesorder");
querybyattribute.ColumnSet = new ColumnSet(new String[] {
"salesorderid", "new_customefield" });
querybyattribute.Attributes.AddRange("ordernumber");
querybyattribute.Values.AddRange(ordernumber);
EntityCollection retrieved = service.RetrieveMultiple(querybyattribute);
foreach (var c in retrieved.Entities)
{
OrderID = new Guid(c.Attributes["salesorderid"].ToString());
CustomFieldValue = c.Attributes["new_customefield"].ToString();
}
推荐答案
发生错误是因为字段没有输入值的对象不会在上下文对象而不是图像中返回。或者说得很清楚-您需要检查属性中是否包含字段。
The error occurs because a field with no entered value won't get returned in the context object not the image. Or to put it graspably - you need to check whether a field is amongst the attributes.
仅通过 ColumnSet声明并请求它是不够的。
It's not sufficient to have declared it and requested it via ColumnSet. It's confusing and annoying (been there myself).
只是我的头顶,我可以想到以下代码片段来管理问题(无需设置)每个读取操作都包含一个 if 子句,但也避免使用一堆方法-每个变量类型都使用一个方法。)
Just of the top of my head, I can think of the following code snippet to manage the issue (without having to set an if clause for every read but also avoiding a bunch of methods - one for each variable type).
private Generic GetEntityValue<Generic>(
Entity entity, String field, Generic substitute = default(Generic))
{
if (entity.Contains(field))
return (Generic)entity[field];
return substitute;
}
编辑:或作为扩展方法
public static T GetAttributeValue<T> (this Entity e, string propertyName, T defaultValue = default(T))
{
if (e.Contains(propertyName))
{
return (T)e[propertyName];
}
else
{
return defaultValue;
}
}
这篇关于使用QueryByAttribute无法检索空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!