Recently I had a requirement where I needed to get related records via a many-to-many (N:N) relationship in Dynamics 365 via a plugin in C#. During my searching online, I kept coming to posts that involved using query expressions. I wanted to do this with LINQ for consistence reasons and readability in my code. I will also add that what I was doing was being done via Associate and Disassociate messages of the plugin. I won't be reviewing that part of the plugin in this post, but I will just be focusing on the LINQ statement used to get the related records via the N:N relationship. Here is the example code that I came up with:
What the above code does, is uses the relationship name (typically setup as prefix_entityOne_enittyTwo), which is the name of the linking table and joins both linked entities together. From that we then filter the records to those that are linked to entity one and return entity two records via the GUID of entity one record. We populate those in a list so we can loop through them or process them as needed.
public List<Entity> GetRelatedRecords(Guid parentID, IOrganizationService service)
{
OrganizationServiceContext context = new OrganizationServiceContext(service);
List<Entity> oProducts = (from r in context.CreateQuery(RELATIONSHIP_NAME)
join eOne in context.CreateQuery(ENTITY_ONE_LOGICALNAME) on r[ENTITY_ONE_UNIQUEID_LOGICALNAME] equals eOne[ENTITY_ONE_UNIQUEID_LOGICALNAME]
join eTwo in context.CreateQuery(ENTITY_TWO_LOGICALNAME) on r[ENTITY_TWO_UNIQUEID_LOGICALNAME] equals eTwo[ENTITY_TWO_UNIQUEID_LOGICALNAME]
where (Guid)eOne[ENTITY_ONE_UNIQUEID_LOGICALNAME] == parentID
select eTwo).ToList();
return oProducts;
}
What the above code does, is uses the relationship name (typically setup as prefix_entityOne_enittyTwo), which is the name of the linking table and joins both linked entities together. From that we then filter the records to those that are linked to entity one and return entity two records via the GUID of entity one record. We populate those in a list so we can loop through them or process them as needed.
This comment has been removed by a blog administrator.
ReplyDeleteI haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. Relationships
ReplyDeleteI simply want to tell you that I am new to weblog and definitely liked this blog site. Very likely I’m going to bookmark your blog . You absolutely have wonderful stories. Cheers for sharing with us your blog. Rachel Rabbit White
ReplyDeleteind out why most guys are poor in the sack and your skill about it. More Over
ReplyDelete