2013-02-26 94 views
4

我是CRM開發新手。除了我的C#應用​​程序中的CRM 2011中的現有值外,我還想更新自定義字段值。如果該字段有一些值,那麼它工作正常,但如果它爲空,那麼我正在接收「給定的密鑰不在字典中。」錯誤。使用QueryByAttribute無法檢索空值

下面的代碼是我想要實現的。

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

Mr.Konrad,非常感謝您的快速反應。我已經使用CustomFieldValue = c.GetAttributeValue (「new_customfield」) ,它的作用就像一個魅力。 – crmdev 2013-02-27 07:26:20

回答

4

錯誤的發生是因爲在不輸入值的字段將不會返回在上下文對象不是圖像。或者說可以理解 - 你需要檢查一個字段是否屬於屬性。

僅通過ColumnSet聲明並請求它是不夠的。這是令人困惑和煩人的(自己在那裏)。

只是我的頭頂,我能想到下面的代碼段來管理問題(而不必設置如果條款,每閱讀,但也避免方法一堆 - 每個變量類型的一個)。

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

+1,僅供參考實體附帶該方法作爲ExtensionMethod開箱即用http://msdn.microsoft.com/en-us/library/gg326129.aspx – glosrob 2013-02-26 13:18:21

+0

@glosrob正確。非常好的一點!我更喜歡使用我的,因爲我可以指定默認值(這對於使用* String *類非常有用 - * n/a *而不是* null *對於非技術用戶而言更不容易混淆)。也許我應該提供代碼來爲該擴展方法創建擴展方法。謹慎編輯我的最多並添加它? ;) – 2013-02-26 13:24:27

+0

那麼,看你是如何。 – glosrob 2013-02-26 14:46:48