2014-05-08 111 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; 
} 
相关问题