Search code examples
pluginsdynamics-crmmicrosoft-dynamics

Plugin Create a relationship record


I need to create a relationship record inside a relationship table.

I have a relationship many-to-many between two table, and I'm trying to do a Create Request inside my plugin to create a new record between the two of them.

I'm creating a Create request in this way:


`Entity entityReference = new Entity("name_of_the_relationship_table");
entityReference["first_table_field"] = Guid("a value of a guid");
entityReference["second_table_field"] = Guid("a value of a guid");

 

service.Create(entityReference);`

when I try to test the plugin i get the error : 'The 'Create' method does not support entities of type 'name_of_the_relationship_table'. MessageProcessorCache returned MessageProcessor.Empty. '


Solution

  • For N:N relationships you need to use the Associate method, this is the documentation page about this https://learn.microsoft.com/en-us/power-apps/developer/data-platform/org-service/entity-operations-associate-disassociate

    sample from the documentation:

       // Retrieve the accounts
    var query = new QueryByAttribute("account")
    {
    ColumnSet = new ColumnSet("name")
    };
    query.AddAttributeValue("address1_city", "Redmond");
    
    EntityCollection accounts = svc.RetrieveMultiple(query);
    
    //Convert the EntityCollection to a EntityReferenceCollection
    var accountReferences = new EntityReferenceCollection();
    
    accounts.Entities.ToList().ForEach(x => {
    accountReferences.Add(x.ToEntityReference());
    });
    
    // The contact to associate to the accounts
    var jimGlynn = new EntityReference("contact", 
    new Guid("cf76763a-ba1c-e811-a954-000d3af451d6"));
    
    // The relationship to use
    var relationship = new Relationship("account_primary_contact");
    
    // Use the Associate method
    svc.Associate(jimGlynn.LogicalName, jimGlynn.Id, relationship, accountReferences);
    

    Keep in mind you need to use the relationship name that may differ from the relationship table