Home > Software engineering >  Retrieve N:N relationship Dynamics CRM/Dataverse C# Plugin
Retrieve N:N relationship Dynamics CRM/Dataverse C# Plugin

Time:12-22

I have a issue I can not seem to resolve myself. I have multiple situations that I need to retrieve N:N data with only the ID of one side of the relationship.

Example: I need to find all Trainees of a Training which is a N:N. I have the Training ID how do I query this?

I tried the following: In this example:
cursist = Trainee
opleiding = Training

if (context.MessageName == "Update" && context.Stage == 20)
    {
        targetEntity = context.InputParameters["Target"] as Entity;

        List<Guid> cursistID = new List<Guid>();
        QueryExpression query = new QueryExpression("cref8_cursist");
        query.ColumnSet = new ColumnSet(new string[] { "cref8_cursistid" });

        LinkEntity linkEntity1 = new LinkEntity("cref8_cursist", "cref8_Opleiding_cref8_Cursist_cref8_Cursi", "cref8_cursistid", "cref8_cursistid", JoinOperator.Inner);
        LinkEntity linkEntity2 = new LinkEntity("cref8_Opleiding_cref8_Cursist_cref8_Cursi", "cref8_opleiding", "cref8_opleidingid", "cref8_opleidingid", JoinOperator.Inner);

        linkEntity1.LinkEntities.Add(linkEntity2);
        query.LinkEntities.Add(linkEntity1);

        linkEntity2.LinkCriteria = new FilterExpression();
        linkEntity2.LinkCriteria.AddCondition(new ConditionExpression("cref8_opleidingid", ConditionOperator.Equal, targetEntity.Id));

        EntityCollection cursistCollection = service.RetrieveMultiple(query);
        if (cursistCollection.Entities.Count > 0)
        {
            foreach (var cursist in cursistCollection.Entities)
            {
                //DO SOME LOGIC
            }
        }

    }

This ends up in the following error: 'The entity with a name = 'cref8_Opleiding_cref8_Cursist_cref8_Cursi' with namemapping = 'Logical' was not found in the MetadataCache.

Best Regards, Anthony

CodePudding user response:

You need only one LinkEntity here.

var query = new QueryExpression("cref8_cursist");
query.ColumnSet.AddColumn("cref8_cursistid");
var intersection = new LinkEntity
{
    LinkFromEntityName = "cref8_cursist",
    LinkToEntityName = "cref8_Opleiding_cref8_Cursist_cref8_Cursi",
    LinkFromAttributeName = "cref8_cursistid",
    LinkToAttributeName = "cref8_cursistid",
    JoinOperator = JoinOperator.Inner
};
intersection.LinkCriteria.AddCondition("cref8_opleidingid", ConditionOperator.Equal, targetEntity.Id);
query.LinkEntities.Add(intersection);
var cursistCollection = service.RetrieveMultiple(query);

Also make sure you have N:N relationship with exactly this name cref8_Opleiding_cref8_Cursist_cref8_Cursi

  • Related