Using QueryByAttribute cannot retrieve null values

泄露秘密 提交于 2019-12-30 10:19:31

问题


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();
}

回答1:


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.

It's not sufficient to have declared it and requested it via ColumnSet. It's confusing and annoying (been there myself).

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;
}

edit: Or as an extension method

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;
    }
}


来源:https://stackoverflow.com/questions/15088408/using-querybyattribute-cannot-retrieve-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!