我是CRM开发的新手。我想从我的C#应用程序更新自定义字段值以及CRM 2011中的现有值。如果该字段有一些值,那么它工作正常,但如果它为null然后我收到“给定的密钥不存在于字典中”。错误。
以下代码是我想要实现的目标。
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();
}
答案 0 :(得分:4)
发生错误是因为没有输入值的字段不会在上下文对象而不是图像中返回。或者说把握 - 你需要检查一个字段是否属于属性。
通过 ColumnSet 声明它并请求它是不够的。这令人困惑和讨厌(自己一直在那里)。
在我的脑海中,我可以想到以下代码片段来管理问题(无需为每次读取设置 if 子句,而且还要避免一堆方法 - 一个对于每种变量类型)。
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;
}
}