Opt Prutal
Opt Prutal

Reputation: 484

How can I use condition and filters in LinkEntity?

I want to create a QueryExpression to simulate this SQL statement

select * from A
inner join B on A.b_id=B.ID
where B.Name like "% what ever %"

this is how the FetchXML might look like

<?xml version="1.0" encoding="UTF-8"?>
<fetch distinct="true" mapping="logical" output-format="xml-platform" version="1.0">
   <entity name="A">
      <attribute name="ID" />
      <attribute name="sce_name" />
      <link-entity name="B" alias="ab" to="b_id" from="A">
         <filter type="and">
            <condition attribute="Name" value="% what ever %" operator="like" />
         </filter>
      </link-entity>
   </entity>
</fetch>

How I can make this in QueryExpression LinkQuery Conditions and Filters, also I don't want to start from B since A might have its conditions too.

This is what I have tried so far

QueryExpression query = new QueryExpression("A");
            query.ColumnSet.AllColumns = true;
            var link = new LinkEntity()
            {
                JoinOperator = JoinOperator.Inner,
                EntityAlias = "c",
                LinkFromEntityName = "A",
                LinkToEntityName = "B",
                LinkFromAttributeName = "b_id",
                LinkToAttributeName = "ID",
            };

             using (var Service = new OrganizationService("con"))
            {
                    EntityCollection entities = Service.RetrieveMultiple(query);
            }

Upvotes: 4

Views: 7119

Answers (2)

Polshgiant
Polshgiant

Reputation: 3664

In addition to James' answer, don't forget you can also query using the fetch statement you already have:

RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
{
    Query = new FetchExpression(
        @"<fetch distinct="true" mapping="logical" output-format="xml-platform" version="1.0">
            <entity name="A">
                ...
            </entity>
         </fetch>");
};

I rarely bother writing out QueryExpressions because executing with fetch is much easier.

Upvotes: 2

James Wood
James Wood

Reputation: 17562

Hopefully this should be self explanatory.

QueryExpression query = new QueryExpression("a") //Start on A
{
    ColumnSet = new ColumnSet(), //Columns to retrieve from A
    Criteria = new FilterExpression(LogicalOperator.And) //Conditions for A
    {
        Conditions =
        {
            new ConditionExpression()
        }
    },
    LinkEntities =
    {
        //Link to B
        new LinkEntity("a", "b", "aid", "bid", JoinOperator.Inner)
        {
            Columns = new ColumnSet(), //Columns to retrieve from B
            LinkCriteria = new FilterExpression() //Conditions for B
            {
                Conditions =
                {
                    new ConditionExpression()
                }
            }
        }
    }
};

Upvotes: 8

Related Questions