March 11, 2014

Microsoft Dynamics CRM 2013 SDK. Retrieve all marketing lists for a campaign

Filed under: Web Content Pages — Tags: , , — Webopius @ 11:25 am

Within Dynamics CRM 2013, there are a number of entities that have N:N relationships. One of these is the CampaignItem entity that connects Campaigns to other Campaigns, Marketing Lists, Products and Sales Literature.

We were writing an API that needs to retrieve all marketing lists for a given campaign from Microsoft Dynamics CRM.

Searching online there were very few articles explaining how to do this using the CRM SDK, so I’ve included an example below in C#. The same principle can probably be applied to any of the N:N entity mappings in Dynamics CRM.

// Get associated Marketing Lists for this campaign...

// The code below works on the basis that you already have a Campaign object in 'campaign'
// _orgService is the CRM OrganizationService object

OrganizationServiceContext context = new OrganizationServiceContext(_orgService);

// Create an Entity reference for the Campaign object
EntityReference er = new EntityReference("campaign", campaign.Id);

// Create Linq Query to retrieve all Marketing Lists mapped to the campaign.
var lists = (from r in context.CreateQuery<List>()
                join s in context.CreateQuery<CampaignItem>() on r.ListId equals s.EntityId
                where s.EntityType == List.EntityLogicalName && s.CampaignId == er
                orderby r.ListId
                select r.ListName
            );
// Display results.
foreach (var list in lists)
{
    Console.WriteLine(list.ToString());
}

That’s it. Hope that other CRM developers find this useful. This same approach should also work across both CRM 2011 and CRM 2013 SDKs.

For custom Microsoft Dynamics CRM software development and project management, please contact Webopius.

  • Tags