Search code examples
dynamics-crmdynamics-crm-2013dynamics-crm-online

Get field name which is related to contact from each entity in dynamics crm using c#


I have one function which gets data as per module name related contacts.

Code:

if (modulename == "lead" || modulename == "opportunity")
{
    contactfield= "parentcontactid";
}
else if (modulename == "salesorder" || modulename == "quote" || modulename == "incident" || modulename == "invoice")
{
    contactfield= = "customerid";
}
else
{
}


quotequery = new QueryExpression()
{
    Distinct = false,
    EntityName = modulename,
    ColumnSet = new ColumnSet(true),
    Criteria =
    {
        Filters = 
        {
            new FilterExpression
            {
                FilterOperator = LogicalOperator.And,
                Conditions = 
                {
                    new ConditionExpression("ownerid", ConditionOperator.Equal, userid),                                
                    new ConditionExpression(contactfield, ConditionOperator.Equal, lstcredential.Contactid.ToString())                                                  
                },
            }           
        }
    }
};
 queryentityCollection = _serviceProxy.RetrieveMultiple(quotequery).Entities;

But for all module there is different different name which is related to contact.for e.g.in lead it is parentcontactid but for invoice it is customerid.

So Is there any solution for fetch attribute name related to contact from entity name?because if else for each entity is not solution as I do in starting.

Please suggest me answer.


Solution

  • If you are looking for a specific contact lookup on a finite set of entities I would hard code it in a name value pair collection similar to what you're doing except maybe a key value pair store:

    private Dictionary<String, String> _contactMappings = new Dictionary<String, String>{"lead", "parentcontactid"}, {"incident", "contactid"};
    

    An alternative would be querying metadata to look for contact lookups, and caching the results, but you wouldn't know which is the correct lookup. For example incident has 3 lookups to contact (contactid, responsiblecontactid, and primarycontactid).