linqdynamics-crmdynamics-crm-2015query-expressions

Translating LINQ query into CRM QueryExpression while using 'select new'


I've got the following container class:

public class AssetAndItsDepositsContainer
    {
        public jp_asset Asset { get; set; }
        public jp_deposit Deposit { get; set; }
    }

Is there a way to take the following LINQ query:

from a in serviceContext.jp_assetSet
join d in serviceContext.jp_depositsSet on a.Id equals d.jp_assetid.Id
where a.statecode == jp_assetState.Active &&
      a.jp_isonhold = true
select new AssetAndItsDepositsContainer()
{
     Asset = a,
     Deposit = d
})
.ToList();

And "translate" it by using QueryExpression? This is what I came up with so far, but I don't know how to mimic the select new expression:

QueryExpression query = new QueryExpression(jp_asset.EntityLogicalName);
query.ColumnSet = new ColumnSet(true);

query.Criteria.AddCondition("statecode", ConditionOperator.Equal, (int)jp_assetState.Active);
query.Criteria.AddCondition("jp_isonhold", ConditionOperator.Equal, true);
LinkEntity link = query.AddLink(jp_deposit.EntityLogicalName, "Id", "jp_assetid", JoinOperator.Inner);

// Now what?
var res = service.RetrieveMultiple(query).Entities; // gets only jp_assets

Solution

  • You can't access an entire LinkEntity, you can only access its attributes as AliasedValue properties on the main Entity itself.

    I would simply retrieve the Id of the second record you're looking for as part of an EntityReference and then execute a Retrieve.