MS CRM 2011 - While clonning how to get associated records when we have 1:N relationship. I have used following code for N:N relationship, by using http://social.msdn.microsoft.com/Forums/en-US/crmdevelopment/thread/96b2c525-b4b2-4768-b9d8-c4a6aac9eb21
Can any one suggest on code changes when 1:N relationship is used.
privatevoidCopyClonedRecords(Entity account)
{
EntityReference clonedAccount=(EntityReference)account["new_clonedaccountid"];
if(clonedAccount !=null&& clonedAccount.Id!=default(Guid))//if no cloned account id, it's not a clone
{
List<Guid> contactIds=GetAssociatedContactIds(clonedAccount.Id);
if(contactIds.Count>0)
{
service.Execute(newAssociateRequest
{
Relationship=newRelationship("new_account_contact"),
Target=newEntityReference("account", account.Id),
RelatedEntities=newEntityReferenceCollection(contactIds.Select(a=>newEntityReference("contact", a)).ToList())
});
}
}
}
privateList<Guid>GetAssociatedContactIds(Guid accountId)
{
List<Guid> contactIds=newList<Guid>();
QueryExpression qe=newQueryExpression("contact");
LinkEntity link1=newLinkEntity
{
LinkFromEntityName="contact",
LinkToEntityName="new_account_contact",
LinkFromAttributeName="contactid",
LinkToAttributeName="contactid"
};
qe.LinkEntities.Add(link1);
LinkEntity link2=newLinkEntity
{
LinkFromEntityName="new_account_contact",
LinkToEntityName="account",
LinkFromAttributeName="accountid",
LinkToAttributeName="accountid"
};
link2.LinkCriteria.AddCondition("accountid",ConditionOperator.Equal, accountId);
link1.LinkEntities.Add(link2);
EntityCollection collection= service.RetrieveMultiple(qe);
if(collection !=null&& collection.Entities!=null&& collection.Entities.Count>0)
{
contactIds= collection.Entities.Select(a=> a.Id).ToList();
}
return contactIds;
}
Thanks, Rajeev