Menu Close

Blog

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

previous arrow
next arrow
Slider

Retrieve related entity records along wih the Primary entity using Retrieve Method

We have always known the Retrieve request to be able to retrieve the data of the requested entity based on the id provided. However in CRM 2011, the Retrieve request can read not only the properties of the primary entity but also the referenced entity like in a 1-N or N-N or N-1 relationship. Given that it supports all the three types of relationships it could be an advantage over the LinkEntity feature.For example, if we want to retrieve the active contacts related to an account then, we can design the query as shown in the below code,

using (OrganizationServiceProxy _orgserviceproxy = new OrganizationServiceProxy(new Uri(OrganizationUri), null, Credentials, null))

                {

                    //create the query expression object
                    QueryExpression query = new QueryExpression();

                    //Query on reated entity records
                    query.EntityName = “contact”;

                    //Retrieve the all attributes of the related record
                    query.ColumnSet = new ColumnSet(true);

                    //create the relationship object
                    Relationship relationship = new Relationship();

                    //add the condition where you can retrieve only the account related active contacts
                    query.Criteria = new FilterExpression();
                    query.Criteria.AddCondition(new ConditionExpression(“statecode”ConditionOperator.Equal,“Active”));

                    // name of relationship between account & contact
                    relationship.SchemaName = “contact_customer_accounts”;

                    //create relationshipQueryCollection Object
                    RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                    //Add the your relation and query to the RelationshipQueryCollection
                    relatedEntity.Add(relationship, query);

                    //create the retrieve request object
                    RetrieveRequest request = new RetrieveRequest();

                    //add the relatedentities query
                    request.RelatedEntitiesQuery = relatedEntity;

                    //set column to  and the condition for the account
                    request.ColumnSet = new ColumnSet(“accountid”);
                    request.Target = new EntityReference { Id = accountID, LogicalName = “account” };

                    //execute the request
                    RetrieveResponse response = (RetrieveResponse)_orgserviceproxy.Execute(request);

                    // here you can check collection count
if (((DataCollection<RelationshipEntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship(“contact_customer_accounts”)) &&((DataCollection<RelationshipEntityCollection>)(((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship(“contact_customer_accounts”)].Entities.Count > 0)
return true;
else
 return false;

 }

One limitation though, is that it is only available with the Retrieve Request and not the Retrieve Multiple request. Wonder why this has not be added for Retrieve Multiple request as this can be of great help to return all the data required in one request.

Share this:

How to retrieve data from multiple entities in CRM

I have an entity called “A” and it has two lookup fields to entities “B” and “C”. Now I want to retrieve data from all the three entities using CRM SDK.

  1. QueryExpression query = new QueryExpression(“EntityALogicalName”);
  2. query.ColumnSet = new ColumnSet(“column1”, “coumn2”);
  3. // Or retrieve All Columns
  4. //query.ColumnSet = new ColumnSet(true);
  5.  
  6. LinkEntity EntityB = new LinkEntity(“EntityALogicalName”, “EntityBLogicalName”, “EntityALinkAttributeName”, “EntityBLinkAttributeName”, JoinOperator.Inner);
  7. EntityB.Columns = new ColumnSet(“column1”, “coumn2”);
  8. EntityB.EntityAlias = “EntityB”;
  9. // Can put condition like this to any Linked entity
  10. // EntityB.LinkCriteria.Conditions.Add(new ConditionExpression(“statuscode”, ConditionOperator.Equal, 1));
  11. query.LinkEntities.Add(EntityB);
  12.  
  13. // Join Operator can be change if there is chance of Null values in the Lookup. Use Left Outer join
  14. LinkEntity EntityC = new LinkEntity(“EntityALogicalName”, “EntityCLogicalName”, “EntityALinkAttributeName”, “EntityCLinkAttributeName”, JoinOperator.Inner);
  15. EntityC.Columns = new ColumnSet(“column1”, “coumn2”);
  16. EntityC.Columns = new ColumnSet(“column1”, “coumn2”);
  17. EntityC.EntityAlias = “EntityC”;
  18. query.LinkEntities.Add(EntityC);
  19.  
  20. query.Criteria.Conditions.Add(new ConditionExpression(“status”, ConditionOperator.Equal, 1));
  21.  
  22. var result = service.RetrieveMultiple(query);
  23.  
  24. foreach (var entity in result.Entities)
  25. {
  26. // Get the Columns from the Entity Obj Like this. Depands on type of the Column.
  27. string entityAColumn1 = entity.Contains(“column1”) ? entity[“column1”].ToString() : string.Empty;
  28. // Use Link Entity Alias with column name
  29. string entityBColumn1 = entity.Contains(“EntityB.column1”) ? (entity[“EntityB.column1”] as AliasedValue).Value.ToString() : string.Empty;
  30. string entityCColumn1 = entity.Contains(“EntityC.column1”) ? (entity[“EntityC.column1”] as AliasedValue).Value.ToString() : string.Empty;
  31. }

 You can use Left Outer join if there is possibility that any lookup values can be Null. You can access the Link Attribute using LinkEntity Alias mention in code. I hope this will also work.

The below Url might give more information and syntax for linked entites 
http://congruentdynamics.blogspot.co.uk/2013/05/retrieve-linked-entity-data-using-query.html

https://lakshmanindian.wordpress.com/2012/11/30/retrieve-data-using-fetchxml-with-multiple-link-entities-in-crm-2011/

Share this:

Micrsoft Dynamics CRM 2011 online – Retrieve Plugin

Retrieve
If  you want to write a plugin that executes every time a user opens a record.

Here is the Retrieve Code

First, create a new Plugin and sign the assembly with a key:


public void Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

if (context.Depth == 1)
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// Obtain the target entity from the input parmameters.
EntityReference entity = (EntityReference)context.InputParameters["Target"];

ColumnSet cols = new ColumnSet(
new String[] { "lastname", "firstname", "address1_name" });

var contact = service.Retrieve("contact", entity.Id, cols);

if (contact != null)
{
if (contact.Attributes.Contains("address1_name") == false)
{
Random rndgen = new Random();
contact.Attributes.Add("address1_name", "first time value: " + rndgen.Next().ToString());
}
else
{
contact["address1_name"] = "i already exist";
}
service.Update(contact);
}
}
}


Next, got to the Plugin Registration Tool (included with the CRM SDK) and register the plugin as follows:

image


What you’ll end up with in this example is:


On first open of the record:


clip_image002


On all future opens of the record:


clip_image002[5]



Share this: