MS Dynamics 365- Disassociate record from N-N relationship entity

Ankaprasad
Posted by Ankaprasad under C# category on | Points: 40 | Views : 39
        /// <summary>
/// Disassociate associated teams from user
/// </summary>
/// <param name="userId">userId</param>
/// <param name="organizationService">organizationService</param>
private static void Disassociate(Guid userId,IOrganizationService organizationService)
{
// N-N Relationship name
string nToNRelationshipName = "xyk_xyk_team_xyk_user";

// Query to get related teams
QueryExpression teams = new QueryExpression("xyk_team");
teams.ColumnSet.AddColumns("xyk_teamid");

// Associated link uisng relationship name , from attribute, to attribute
var associateLink = teams.AddLink(nToNRelationshipName, "xyk_teamid", "xyk_teamid");
associateLink.LinkCriteria = new FilterExpression() { Conditions = { new ConditionExpression("xyk_userid", ConditionOperator.Equal, userId) } };

// Retrieve associated teams
EntityCollection associatedTeams = organizationService.RetrieveMultiple(teams);

if (associatedTeams.Entities.Count > 0)
{
EntityReferenceCollection teamsCollection = new EntityReferenceCollection();
foreach (Entity team in associatedTeams.Entities)
{
var reference = new EntityReference("xyk_team", team.Id);
teamsCollection.Add(reference);
}

Relationship nIsToNRelationship = new Relationship(nToNRelationshipName);
// Disassociate associated teams from user
organizationService.Disassociate("xyk_user", userId, nIsToNRelationship, teamsCollection);
}
}

Comments or Responses

Login to post response