在我的 CRM 中,我有一个与具有 N:N 关系的“联系人”实体相关的“顾问”实体。创建 Advisor 实体后,我使用以下代码将 Advisor 关联到 Contact:
_service.Associate("contact", contactid, relationship, relatedAdvisors);
relatedAdvisors 是一个实体引用集合。但是,如果关系已经存在,则会出现错误,
"Cannot insert duplicate Key"
我如何检查此顾问是否已与联系人相关联?
请您参考如下方法:
以下查询应该适合您。但是我没有编译它,但你可以得到一个想法。
// 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);
注意
我没有编译这段代码,因为目前我无法访问开发系统。但它可能会帮助您获得灵感。
