web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Retrieve records from multiple tables

(1) ShareShare
ReportReport
Posted on by 12,119 Moderator

Hi all

I want to retrieve records from multiple table with the help of relation between tables. I want to write custom workflow for this requirement. How can I write custom workflow for retrieving records from multiple table with the help of relation between tables. 

This is my relational database diagram for retrieving records.

2555.Untitled7.png

Thank You

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Nithya Gopinath Profile Picture
    17,078 on at

    Hi Abdul Wahab,

    You can write c# code to retrieve records from multiple tables. Please refer the link below.

    msdn.microsoft.com/.../gg328446.aspx

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Nithya Gopinath and all


    I use this code to retrieve single record

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;// use for web exception
    using System.IO; // use for StreamReader
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;
    using System.Activities;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Messages;

    namespace CreateListMembers
    {
    class ListMembers : CodeActivity
    {
    protected override void Execute(CodeActivityContext context)
    {
    ITracingService tracingService = context.GetExtension<ITracingService>();
    IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
    IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
    IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

    //Retrieve the contact id
    Guid listIdd = workflowContext.PrimaryEntityId;

    //Create the request
    RetrieveRequest request = new RetrieveRequest();
    request.ColumnSet = new ColumnSet(new string[] { "aw_name", "aw_campaign", "aw_fromname", "aw_subject", "aw_fromemail" });
    request.Target = new EntityReference(EntityName.list, listIdd);

    //Retrieve the entity to determine what the birthdate is set at
    Entity entity = (Entity)((RetrieveResponse)service.Execute(request)).Entity;
    var aw_name = entity[ContactAttributes.aw_name];
    var aw_campaign = entity[ContactAttributes.aw_Campaign];
    var aw_fromname = entity[ContactAttributes.aw_FromName];
    var aw_subject = entity[ContactAttributes.aw_Subject];
    var aw_fromemail = entity[ContactAttributes.aw_Fromemail];

    }

    }

    public static class EntityName
    {

    public const string list = "list";
    }

    public static class ContactAttributes
    {
    public const string aw_name = "aw_name";
    public const string aw_Campaign = "aw_campaign";
    public const string aw_FromName = "aw_fromname";
    public const string aw_Subject = "aw_subject";
    public const string aw_Fromemail = "aw_fromemail";
    }

    }

     

    but How can I use it  for retrieving records from multiple table with the help of relation between tables?

     

    Thank You

     

  • Suggested answer
    Alagunellaikumar Profile Picture
    6,212 on at

    Hi

    You can use LinkEntities as similar to SQL JOIN

    Could you please refer the below link?

    msdn.microsoft.com/.../gg328149.aspx

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Alagu nellaikumar.S

    What is this "_orgService"?

    May You please explain?

    3443.2.png

    Thank You

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Alagu nellaikumar.S

    It should be IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

    Sorry for disturbing You

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Alagu nellaikumar.S, Nithya Gopinath and all

    I am using this code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;// use for web exception
    using System.IO; // use for StreamReader
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;
    using System.Activities;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Messages;

    namespace CreateListMembers
    {
    public class ListMembers : CodeActivity
    {
    protected override void Execute(CodeActivityContext context)
    {
    string dataCenter = "us";
    string apiKey = "ab15c4d1398b952ca886a92e5a";
    string firstname = "";
    string lastname ="";
    string emailaddress1 ="";
    string listid = "";


    ITracingService tracingService = context.GetExtension<ITracingService>();
    IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
    IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
    IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);
    //<>
    //Create a query expression specifying the link entity alias and the columns of the link entity that you want to return
    QueryExpression qe = new QueryExpression();
    qe.EntityName = EntityName.mailchimpList;
    qe.ColumnSet = new ColumnSet();
    qe.ColumnSet.AddColumns(mailchimpListAttributes.aw_mailchimpId, mailchimpListAttributes.aw_listid);

    qe.LinkEntities.Add(new LinkEntity(EntityName.mailchimpList, EntityName.list, mailchimpListAttributes.aw_mailchimpId, listAttributes.listid, JoinOperator.Inner));
    qe.LinkEntities[0].Columns.AddColumns(listAttributes.listid, listAttributes.createdfromcode);

    qe.LinkEntities[0].EntityAlias = "memberType";

    qe.LinkEntities.Add(new LinkEntity(EntityName.list, EntityName.listmember, listAttributes.listid, listMemberAttributes.listid, JoinOperator.Inner));
    qe.LinkEntities[0].Columns.AddColumns(listMemberAttributes.listid, listMemberAttributes.entityid);
    qe.LinkEntities[0].EntityAlias = "memberType";

    EntityCollection ec = service.RetrieveMultiple(qe);
    foreach (Entity memberType in ec.Entities)
    {
    var MemberType = memberType["memberType.createdfromcode"].ToString();
    listid = memberType["memberType.aw_listid"].ToString();
    if (MemberType == "4")
    {
    qe.LinkEntities.Add(new LinkEntity(EntityName.listmember, EntityName.lead, listMemberAttributes.entityid, leadAttributes.leadid, JoinOperator.Inner));
    qe.LinkEntities[0].Columns.AddColumns(leadAttributes.leadid, leadAttributes.firstname, leadAttributes.lastname, leadAttributes.emailaddress1);

    qe.LinkEntities[0].EntityAlias = "mailchimpList";

    EntityCollection ecc = service.RetrieveMultiple(qe);
    foreach (Entity MailChimpList in ecc.Entities)
    {
    firstname = MailChimpList["mailchimpList.firstname"].ToString();
    lastname = MailChimpList["mailchimpList.lastname"].ToString();
    emailaddress1 = MailChimpList["mailchimpList.emailaddress1"].ToString();

    var sampleListMember = JsonConvert.SerializeObject(
    new
    {
    email_address = emailaddress1,
    merge_fields =
    new
    {
    FNAME = firstname,
    LNAME = lastname
    },
    status_if_new = "subscribed"
    });

    var hashedEmailAddress = string.IsNullOrEmpty(emailaddress1) ? "" : CalculateMD5Hash(emailaddress1.ToLower());
    var urii = string.Format("https://{0}.api.mailchimp.com/3.0/lists/{1}/members/{2}", dataCenter, listid, hashedEmailAddress);
    try
    {
    using (var webClient = new WebClient())
    {
    webClient.Headers.Add("Accept", "application/json");
    webClient.Headers.Add("Authorization", "apikey " + apiKey);

    webClient.UploadString(urii, "PUT", sampleListMember);
    //Console.ReadLine();
    }
    }
    catch (WebException we)
    {
    using (var sr = new StreamReader(we.Response.GetResponseStream()))
    {
    Console.WriteLine(sr.ReadToEnd());
    }
    }
    }
    }
    }
    }

    private static string CalculateMD5Hash(string input)
    {
    // Step 1, calculate MD5 hash from input.
    var md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hash = md5.ComputeHash(inputBytes);

    // Step 2, convert byte array to hex string.
    var sb = new StringBuilder();
    foreach (var @byte in hash)
    {
    sb.Append(@byte.ToString("X2"));
    }
    return sb.ToString();
    }
    }

    public static class EntityName
    {

    public const string mailchimpList = "aw_mailchimp";
    public const string list = "list";
    public const string listmember = "listmember";
    public const string lead = "lead";
    }

    public static class mailchimpListAttributes
    {
    public const string aw_mailchimpId = "aw_mailchimpid";
    public const string aw_listid = "aw_listid";
    }
    public static class listAttributes
    {
    public const string listid = "listid";
    public const string createdfromcode = "createdfromcode";
    }
    public static class listMemberAttributes
    {
    public const string listid = "listid";
    public const string entityid = "entityid";
    }
    public static class leadAttributes
    {
    public const string leadid = "leadid";
    public const string firstname = "firstname";
    public const string lastname = "lastname";
    public const string emailaddress1 = "emailaddress1";

    }

    }

    and getting this error

    6170.3.png

    I know the meaning of this error. but not able to find the line of code which make this error.

    Please help me to solve my issue.

    Thank You

  • Suggested answer
    tw0sh3ds Profile Picture
    5,600 on at

    Hi,

    Here:

    qe.LinkEntities.Add(new LinkEntity(EntityName.list, EntityName.listmember, listAttributes.listid, listMemberAttributes.listid, JoinOperator.Inner));

    qe.LinkEntities[0].Columns.AddColumns(listMemberAttributes.listid, listMemberAttributes.entityid);

    qe.LinkEntities[0].EntityAlias = "memberType";

    You are adding new LinkEntities and referring still to the [0] index which is not your new LinkEntity. Writing a code like that is very prone to errors, you should create your LinkEntity object, set all properties the way you want and then add it to the list of LinkEntities. Not add them and then set the properties.

  • Suggested answer
    Nithya Gopinath Profile Picture
    17,078 on at

    Hi,

    This occurs if you don't specify a certain field/column in the Column-Set of Query Expression but  retrieves this field/column for every entity record of the Entity Collection obtained by executing the query expression.

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Pawel Gradecki, Nithya Gopinath, Alagu nellaikumar.S and all

    1. I have a table name "aw_mailchimp". I want to retrieve axp_axpulsemailchimpid and aw_listid from aw_mailchimp.

    2. I also have table name "list". I want to retrieve listid and createdfromcode from list.

    3. I also have a table name "listmember". I want to retrieve listid and entityid from listmember.

    4. I also have a table name "lead". I want to retrieve leadid, firstname, lastname and emailaddress1 from lead.

    Relational diagram is present over there 

    7215.aa.png

    I am using this code but not able to fulfill my requirement. Please help me in making this situation

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;// use for web exception
    using System.IO; // use for StreamReader
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;
    using System.Activities;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Messages;

    namespace CreateListMembers
    {
    public class ListMembers : CodeActivity
    {
    protected override void Execute(CodeActivityContext context)
    {
    //string subscriberEmail = "abdulwahabubit@outlook.com";
    string dataCenter = "u4";
    string apiKey = "ab15c4d1322ca886a92e5a";
    string firstname = "";
    string lastname ="";
    string emailaddress1 ="";
    string listid = "";


    ITracingService tracingService = context.GetExtension<ITracingService>();
    IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
    IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
    IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);
    //<>
    //Create a query expression specifying the link entity alias and the columns of the link entity that you want to return
    QueryExpression qe = new QueryExpression();
    qe.EntityName = EntityName.mailchimpList;
    qe.ColumnSet = new ColumnSet();
    qe.ColumnSet.AddColumns(mailchimpListAttributes.aw_mailchimpId, mailchimpListAttributes.aw_listid, mailchimpListAttributes.aw_name, mailchimpListAttributes.aw_FromName);

    qe.LinkEntities.Add(new LinkEntity(EntityName.mailchimpList, EntityName.list, mailchimpListAttributes.aw_mailchimpId, listAttributes.listid, JoinOperator.Inner));
    qe.LinkEntities[0].Columns.AddColumns(listAttributes.listid, listAttributes.createdfromcode);
    qe.LinkEntities[0].EntityAlias = "memberType";

    EntityCollection ec = service.RetrieveMultiple(qe);

    //Console.WriteLine("Retrieved {0} entities", ec.Entities.Count);
    foreach (Entity MailChimplList in ec.Entities)
    {
    //Console.WriteLine("account name:" + act["name"]);
    Entity contact = new Entity("contact");
    contact["firstname"] = MailChimplList[mailchimpListAttributes.aw_name];
    //Console.WriteLine("primary contact first name:" + act["primarycontact.firstname"]);
    contact["lastname"] = MailChimplList[mailchimpListAttributes.aw_FromName];
    //Console.WriteLine("primary contact last name:" + act["primarycontact.lastname"]);


    //contact["lastname"] = "current record";

    Guid contactId = service.Create(contact);
    }

    //<>

    //</>

    qe.LinkEntities.Add(new LinkEntity(EntityName.list, EntityName.listmember, listAttributes.listid, listMemberAttributes.listid, JoinOperator.Inner));
    // sooposition for error
    //qe.LinkEntities[0].Columns.AddColumns(listMemberAttributes.listid, listMemberAttributes.entityid);
    qe.LinkEntities[1].Columns.AddColumns(listMemberAttributes.listid, listMemberAttributes.entityid);
    qe.LinkEntities[1].EntityAlias = "memberType";

    EntityCollection ec = service.RetrieveMultiple(qe);
    foreach (Entity memberType in ec.Entities)
    {
    var MemberType = memberType["memberType.createdfromcode"].ToString();
    listid = memberType["memberType.aw_listid"].ToString();
    if (MemberType == "4")
    {
    qe.LinkEntities.Add(new LinkEntity(EntityName.lead, EntityName.listmember, listMemberAttributes.entityid, leadAttributes.leadid, JoinOperator.Inner));
    qe.LinkEntities[2].Columns.AddColumns(leadAttributes.leadid, leadAttributes.firstname, leadAttributes.lastname, leadAttributes.emailaddress1);

    qe.LinkEntities[2].EntityAlias = "mailchimpList";

    EntityCollection ecc = service.RetrieveMultiple(qe);
    foreach (Entity MailChimpList in ecc.Entities)
    {
    firstname = MailChimpList["mailchimpList.firstname"].ToString();
    lastname = MailChimpList["mailchimpList.lastname"].ToString();
    emailaddress1 = MailChimpList["mailchimpList.emailaddress1"].ToString();

    var sampleListMember = JsonConvert.SerializeObject(
    new
    {
    email_address = emailaddress1,
    merge_fields =
    new
    {
    FNAME = firstname,
    LNAME = lastname
    },
    status_if_new = "subscribed"
    });

    var hashedEmailAddress = string.IsNullOrEmpty(emailaddress1) ? "" : CalculateMD5Hash(emailaddress1.ToLower());
    var urii = string.Format("https://{0}.api.mailchimp.com/3.0/lists/{1}/members/{2}", dataCenter, listid, hashedEmailAddress);
    try
    {
    using (var webClient = new WebClient())
    {
    webClient.Headers.Add("Accept", "application/json");
    webClient.Headers.Add("Authorization", "apikey " + apiKey);

    webClient.UploadString(urii, "PUT", sampleListMember);
    //Console.ReadLine();
    }
    }
    catch (WebException we)
    {
    using (var sr = new StreamReader(we.Response.GetResponseStream()))
    {
    Console.WriteLine(sr.ReadToEnd());
    }
    }
    }
    }
    }
    }

    private static string CalculateMD5Hash(string input)
    {
    // Step 1, calculate MD5 hash from input.
    var md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hash = md5.ComputeHash(inputBytes);

    // Step 2, convert byte array to hex string.
    var sb = new StringBuilder();
    foreach (var @byte in hash)
    {
    sb.Append(@byte.ToString("X2"));
    }
    return sb.ToString();
    }
    }

    public static class EntityName
    {

    public const string mailchimpList = "aw_mailchimp";
    public const string list = "list";
    public const string listmember = "listmember";
    public const string lead = "lead";
    }

    public static class mailchimpListAttributes
    {
    public const string aw_mailchimpId = "aw_mailchimpid";
    public const string aw_listid = "aw_listid";
    public const string aw_name = "aw_name";
    public const string aw_FromName = "aw_fromame";
    }
    public static class listAttributes
    {
    public const string listid = "listid";
    public const string createdfromcode = "createdfromcode";
    }
    public static class listMemberAttributes
    {
    public const string listid = "listid";
    public const string entityid = "entityid";
    }
    public static class leadAttributes
    {
    public const string leadid = "leadid";
    public const string firstname = "firstname";
    public const string lastname = "lastname";
    public const string emailaddress1 = "emailaddress1";

    }

    }

    Thank You

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi all

    I am using this code

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Net;// use for web exception

    using System.IO; // use for StreamReader

    using System.Threading.Tasks;

    using Newtonsoft.Json;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Workflow;

    using System.Activities;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Xrm.Sdk.Messages;

    namespace CreateListMembers

    {

       public class ListMembers : CodeActivity

       {

           protected override void Execute(CodeActivityContext context)

           {

               ITracingService tracingService = context.GetExtension<ITracingService>();

               IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();

               IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();

               IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

               var query = new QueryExpression("aw_mailchimp");

               LinkEntity linkEntityaw_mailchimp = new LinkEntity()

               {

                   LinkFromEntityName = "aw_mailchimp",

                   LinkFromAttributeName = "aw_mailchimpid",

                   LinkToEntityName = "list",

                   LinkToAttributeName = "aw_mailchimmarkettinglistid",

                   JoinOperator = JoinOperator.Inner,

               };

               LinkEntity linkEntityList = new LinkEntity()

               {

                   LinkFromEntityName = "list",

                   LinkFromAttributeName = "listid",

                   LinkToEntityName = "listmember",

                   LinkToAttributeName = "listid",

                   JoinOperator = JoinOperator.Inner,

                   //Columns = new ColumnSet(colsAccount),

                   //EntityAlias = "Contacts"

               };

               query.LinkEntities.Add(linkEntityList);

               EntityCollection _results = service.RetrieveMultiple(query);

               if (_results != null)

               {

                   foreach (var ent in _results.Entities)

                   {

                       // Display “First Name” along with Alias

                       //Console.WriteLine((ent.Attributes["Contacts.firstname"] as AliasedValue).Value);

                       // Display “Last Name” along with Alias

                       //Console.WriteLine((ent.Attributes["Contacts.lastname"] as AliasedValue).Value);

                   }

               }

           }

       }

    }

    It is giving me this error

    5141.aa.png

    Here I am not requiring attribute listid then Why it is giving me listid error on mailchimp entity?

    Please help me.

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans