Tuesday, March 26, 2013

CRM 2011: Associate/Disassociate entities from a relation C#

In my exact requirement I had a N:N relation between 2 entities and I had to associate/disassociate entities that are connected with this N:N relation.
Here are two methods for this.


 public static void DisassociateEntitiesToTarget(EntityReference target, EntityReferenceCollection relatedEntities, string relationName, IOrganizationService service)
        {

            // Add the relationship schema name
            Relationship relationship = new Relationship(relationName);

            // Disassociate the entities records to target
            service.Disassociate(target.LogicalName, target.Id, relationship, relatedEntities);

        }

Call the method
DisassociateEntitiesToTarget(targetEntity.ToEntityReference(), relatedEntities, "relationName", utils.Service);

        public static void AssociateEntitiesToTarget(EntityReference target, EntityReferenceCollection relatedEntities, string relationName, IOrganizationService service)
        {

            // Add the relationship schema name
            Relationship relationship = new Relationship(relationName);
         
            // Associate the entities to target
            service.Associate(target.LogicalName, target.Id, relationship, relatedEntities);
         
        }

Call the method:
AssociateEntitiesToTarget(targetEntity.ToEntityReference(), entitiesToAssociate, "relationName", utils.Service);

No comments:

Post a Comment