使用“select new”将LINQ查询转换为CRM QueryExpression

时间:2017-07-03 10:14:37

标签: linq dynamics-crm dynamics-crm-2015 query-expressions

我有以下容器类:

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

有没有办法采用以下LINQ查询:

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();

使用QueryExpression“翻译”它? 这是我到目前为止所提出的,但我不知道如何模仿select new表达式:

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

2 个答案:

答案 0 :(得分:1)

您无法访问整个LinkEntity,只能在AliasedValueEntity上将其属性作为EntityReference属性进行访问。

我只是在from itertools import chain, combinations tasks = { "A": 25, "B": 20, "C": 25, "D": 35, "E": 25, "F": 30, "G": 30 } def powerset(iterable): s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) def get_possible_tasks(fixed_duration): for comb in powerset(tasks): if sum([tasks[i] for i in comb]) == fixed_duration: yield comb def get_possible_tasks_inrange(min_duration, max_duration): for comb in powerset(tasks): if min_duration <= sum([tasks[i] for i in comb]) <= max_duration: yield comb print("TASKS completed in onehour") for i in get_possible_tasks(60): print(i) print("TASKS In RANGE 60-120 minutes") for i in get_possible_tasks_inrange(60,120): print(i) 中检索您要查找的第二条记录的ID,然后执行Retrieve

答案 1 :(得分:1)

您实际上可以从链接的实体构造有效的Entity个对象。唯一的要求是链接实体的主键必须在结果集中可用。

因此,您的代码段可以像这样扩展:

var query = new QueryExpression(jp_asset.EntityLogicalName);
query.ColumnSet.AllColumns = 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);
link.EntityAlias = "d";
link.Columns.AddColumns("jp_depositid", "jp_name");

IEnumerable<Entity> deposits = Service.RetrieveMultiple(query).Entities
    .Select(e => new Entity("jp_deposit")
    {
        Id = (Guid)e.GetAttributeValue<AliasedValue>("d.jp_depositid").Value,
        ["jp_name"] = e.GetAttributeValue<AliasedValue>("d.jp_name")?.Value
    });
  

注意

     

上面的示例仅对内部联接有效。在结果集中,链接实体的主键(ID)将始终可用。因此,使用.Value语法获取其值是安全的。可以使用?.Value检索所有其他属性值。

     

对于左连接,您需要在执行Select之前先过滤结果集。