Skip to main content

Retrieve, Associate, Disassociate N:N Related Records using C#

 URL

retrieve

QueryExpression query = new QueryExpression("list"); //Name of the entity to be passed whose records need to be retrieved

var nIsToNRelationshipName="cdi_emailsend_suppressed_list"; //schema name of N:N relationship

query.ColumnSet = new ColumnSet(true);

var link = query.AddLink(nIsToNRelationshipName, "listid", "listid");

//Method Signature: AddLink("N:N schema name to be passed", "Primary key ID schema name of entity record to be retrieved", "schema name of attribute in the N:N relationship")

Guid emailSendID = new Guid("79121c07-220e-41ae-9710-96b880973e6c"); //sample ID of Email Send record for which we are retrieving related records

link.LinkCriteria = new FilterExpression()

{

Conditions =

{

new ConditionExpression("cdi_emailsendid", ConditionOperator.Equal, emailSendID)

// Filter condition to get related marketing lists of an Email Send record

}

};

 

EntityCollection collRecords = service.RetrieveMultiple(query);

if (collRecords != null && collRecords.Entities != null && collRecords.Entities.Count > 0)

{

foreach (var entity in collRecords.Entities)

{

// Do something

}

}

disassociate

EntityCollection collRecords = service.RetrieveMultiple(query);

if (collRecords != null && collRecords.Entities != null && collRecords.Entities.Count > 0)

{

EntityReferenceCollection collection = new EntityReferenceCollection();

foreach (var entity in collRecords.Entities)

{

var reference = new EntityReference("list", entity.Id);

collection.Add(reference); //Create a collection of entity references

}

Relationship relationship = new Relationship("cdi_emailsend_suppressed_list"); //schema name of N:N relationship

service.Disassociate("cdi_emailsend", emailSendID, relationship, collection); //Pass the entity reference collections to be disassociated from the specific Email Send record

}


associate


Guid marketingListID= new Guid("79abbc07-220e-41ae-9710-96b540973e6c"); //GUID of marketing list to be associated
 
AssociateRequest request = new AssociateRequest
{
Target = new EntityReference("cdi_emailsend", emailSendID),
RelatedEntities = new EntityReferenceCollection
{
new EntityReference("list", marketingListID)
},
Relationship = new Relationship("cdi_emailsend_suppressed_list")
};
 
service.Execute(request);

Comments