2014-05-08 147 views
0

在我的CRM中,我有一個「顧問」實體,它與具有N:N關係的「聯繫人」實體相關。創建顧問單位後,我的顧問關聯與下面的代碼聯繫方式:如何檢查一個關係是否已經存在?

_service.Associate("contact", contactid, relationship, relatedAdvisors); 

relatedAdvisors是一個實體引用的集合。但是,如果關係已經存在,我得到的錯誤,

「無法插入重複鍵」

我如何檢查是否該顧問已經與接觸?

回答

2

以下查詢應該適合您。但是我沒有編譯它,但你可以得到一個想法。

// Create new object of RelatedAdvisors 
var newRelatedAdvisors = new new_RelatedAdvisors(); 

// Go through all the advisors in colletion 
foreach(var advisor in relatedAdvisors) 
{ 
    // Search of existing relationship between contact and advisor 
    var existingAdvisor = (from a in linqContext.CreateQuery<new_RelatedAdvisors>() where a.contactid == contactid && a.Id == advisor.Id select a).FirstOrDefault(); 

    // if relationship does not exist then add add advisor to newly created collection object 
    if(xyz == null || xyz.Count() == 0) 
    { 
     // Add advisor to newRelatedAdvisors 
    } 
} 
// associate the contact with newly created collection of relatedadvisors 
_service.Associate("contact", contactid, relationship, newRelatedAdvisors); 

注意

,因爲目前我沒有獲得發展的系統我還沒有編譯此代碼。但它可能會幫助你獲得想法。

+0

對不起,我不太明白這一點。我假設xyz將持有相關顧問的集合。我相信這不會是一個準確的檢查,如果現有的xyz包含顧問A,B和C,而我的新相關顧問是D,E和F,該怎麼辦?我們不是在這裏只檢查這個聯繫人是否與顧問有任何關係,但我們實際上並沒有檢查現有的關係? – user3340627

+0

嗨,只是編輯了代碼。不過,您需要進行更改以使其正常工作,因爲我目前沒有開發者設置。我也喜歡@Andrii Butenko提供的解決方案。我相信該解決方案將對您有所幫助,因爲這是編譯代碼 – Scorpion

+0

謝謝您的回答。我無法使用「linqContext」這是一個內置對象嗎?對不起,我是一個CRM初學者 – user3340627

0

希望這將幫助:

private static bool RelationshipExists(IOrganizationService service, string relationshipname, Guid entity1Id, string entity1Name, Guid entity2Id, string entity2Name) 
{ 
    string relationship1EtityName = string.Format("{0}id", entity1Name); 
    string relationship2EntityName = string.Format("{0}id", entity2Name); 

    //This check is added for self-referenced relationships 
    if (entity1Name.Equals(entity2Name, StringComparison.InvariantCultureIgnoreCase)) 
    { 
     relationship1EtityName = string.Format("{0}idone", entity1Name); 
     relationship1EtityName = string.Format("{0}idtwo", entity1Name); 
    } 

    QueryExpression query = new QueryExpression(entity1Name) { ColumnSet = new ColumnSet(false) }; 

    LinkEntity link = query.AddLink(relationshipname, 
    string.Format("{0}id", entity1Name), relationship1EtityName); 

    link.LinkCriteria.AddCondition(relationship1EtityName, 
    ConditionOperator.Equal, new object[] { entity1Id }); 

    link.LinkCriteria.AddCondition(relationship2EntityName, 
    ConditionOperator.Equal, new object[] { entity2Id }); 

    return service.RetrieveMultiple(query).Entities.Count != 0; 
} 
相關問題