Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Unanswered

Dessasociate plugin

(2) ShareShare
ReportReport
Posted on by 19
Hi.
I have Table A that's linked to three tables with N:N relationships. When I create a record in Table A through a Power Automate flow, I link Table A to the other three.
This works perfectly. I had the problem that when deleting the record from Table A, it gave a constraint error due to the related tables.
 
I created a plugin to disassociate the three tables associated with Table A before deleting the record.

The problem I'm having now is that the plugin works correctly, but when I view the records in the related tables, I see that one table still has the records.
 
The odd thing is that it lets me delete the record from Table A without giving a constraint error.
 
What could be happening?
 

This is the code I use to disassociate:
 
private void EliminarRelacionesNN( EntityReference entityRef, IOrganizationService service, List<string> relationshipName )
{
    try
    {
        foreach ( string relationship in relationshipName )
        {
            tracingService.Trace( $"Target: {entityRef.LogicalName};  Relación: {relationship}" );
            // Crear la solicitud para eliminar TODAS las asociaciones N:N
            var disassociateRequest = new DisassociateRequest
            {
                Target = entityRef,                                     // Tabla desde la que se está eliminando
                Relationship = new Relationship( relationship ),        // Nombre de la relación
                RelatedEntities = new EntityReferenceCollection( )      // Se eliminan todas las relaciones
            };

            // Ejecutar la eliminación de las relaciones N:N
            var resultado = service.Execute( disassociateRequest );
            tracingService.Trace( $"Eliminación correcta de la entidad: {relationship}" );
        }
    }
    catch ( Exception ex )
    {
        tracingService.Trace( $"Error borrando tablas relacionadas: {ex.Message}" );
        throw new InvalidPluginExecutionException( $"Error FOREACH borrando tabla relacionadas: {ex.Message}" );
    }
}
  • CU14030949-0 Profile Picture
    19 on at
    Dessasociate plugin
    Hello, Holly, and thank you very much for your reply.
    I followed your advice and modified the coding so that it first retrieves the associated records and then detaches them.
    Here's the code.
     
    foreach ( var relationship in relaciones )
    {
                    tracingService.Trace( $"Procesando relación: {relationship.NombreRelacion};  Tabla: {relationship.NombreTabla}" );
                    tracingService.Trace( $"Id del registro a buscar: {entityRef.Id}" );
                    // Obtener los registros relacionados
                    var query = new QueryExpression
                    {
                        EntityName = relationship.NombreTabla,  // Nombre de la tabla relación N:N
                        ColumnSet = new ColumnSet( false ),
                        Criteria = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression(entityRef.LogicalName + "id", ConditionOperator.Equal, entityRef.Id)
                            }
                        }
                    };
                    EntityCollection relatedEntities = service.RetrieveMultiple( query );
                    
                    tracingService.Trace( $"Ejecutada retrievemultiple para '{relationship.NombreRelacion}'" );
                    if ( relatedEntities.Entities.Count > 0 )
                    {
                        //tracingService.Trace( $"Id del registro de la tabla intermedia: {relatedEntities.Entities[0].Id}" );
                        var relatedEntityRefs = relatedEntities.Entities.Select( e => e.ToEntityReference( ) ).ToList( );
                        tracingService.Trace( $"Se encontraron {relatedEntityRefs.Count} registros relacionados en {relationship.NombreRelacion}" );
                        var disassociateRequest = new DisassociateRequest
                        {
                            Target = entityRef,
                            Relationship = new Relationship( relationship.NombreRelacion ),
                            RelatedEntities = new EntityReferenceCollection( relatedEntityRefs )
                        };
                        var respuesta = service.Execute( disassociateRequest );
                        tracingService.Trace( $"Relación {relationship.NombreRelacion} eliminada correctamente." );
                    }
                    else
                    {
                        tracingService.Trace( $"No hay registros en {relationship.NombreRelacion} para eliminar." );
                    }
    }
     
    The problem persists. Of the three tables, two detach correctly, but the third retains its data. I've looked at flows, actions, etc., and haven't seen any problems. I specifically created this plugin because there's no "before" delete event in either JavaScript or Power Automate.
  • Holly Huffman Profile Picture
    3,754 on at
    Dessasociate plugin
    Hi there! Good morning, evening, or afternoon - depending on where you are :) Hope you are well today! 
     
    It sounds like you've been thorough with your plugin setup, and you're close to pinpointing the issue. Based on the behavior described, here are some insights and suggestions:
    • Issue with Disassociation Logic: Even though your plugin works without throwing errors, it's possible that the RelatedEntities parameter in the DisassociateRequest is being treated as empty. Since you're not explicitly adding related records to the EntityReferenceCollection, the plugin might not be targeting any related entities in certain cases.
      To ensure all relationships are being disassociated, try modifying the plugin to retrieve the current N:N associations before executing the DisassociateRequest. Here’s a conceptual update:
      • Retrieve the related entities using RetrieveMultipleRequest for each relationship.
      • Populate the RelatedEntities collection with the retrieved entities before executing the disassociate request.
    • Silent Failures: Check whether the service call for disassociation silently fails for the specific table that retains records. Add more detailed tracing to confirm if the DisassociateRequest is executed as expected for all three relationships. For example:

      tracingService.Trace($"Disassociating records for relationship: {relationship}");
     
    • Unexpected Constraints: Ensure there are no other constraints or custom business logic (e.g., workflows, plugins) affecting the records in the table that retains relationships. Sometimes, other processes might interfere with or overwrite the plugin's actions.
    • Data Integrity Issue: If disassociation for a specific relationship works inconsistently, there might be underlying data integrity issues. Run diagnostics to confirm if all relationships in that table are correctly mapped and there are no orphaned records.
    • Plugin Scope: Confirm that your plugin is set to trigger with the correct scope (e.g., parent entity and all related tables). If the plugin scope is misconfigured, it might miss disassociating relationships for specific tables.
    • Test in Isolation: Temporarily create a simplified test plugin for the problematic relationship to verify its behavior in isolation. This can help narrow down whether the issue lies within the plugin logic, Power Automate flow, or related table setup.
     
     hope this helps! 
     
     

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

🌸 Community Spring Festival 2025 Challenge 🌸

WIN Power Platform Community Conference 2025 tickets!

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 293,304 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 232,160 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Product updates

Dynamics 365 release plans