Linq谓词查询结果不适用于进一步的Linq Join

时间:2015-06-12 09:24:28

标签: c# linq dynamics-crm-2011 predicate linqkit

我使用Predicate查询的结果在Linq查询中编写连接。但它抛出以下错误。但是,当我在SQL中运行类似的查询时,它返回预期的结果。

var predicate = PredicateBuilder.False<Product>();
foreach (var productId in productIds)
{
    var tempGuid = productId;
    predicate = predicate.Or(p => p.ProductId== tempGuid.ToString());
}

// This query is returning products back
var products = from p in context.ProductSet.AsExpandable().Where(predicate)
                           select p;

var accounts = (from a in context.AccountSet
                join cl in context.ContractDetailSet 
                on a.AccountId equals cl.AccountId.Id
                join p in products on  \\ From predicate query
                cl.ProductId.Id equals p.ProductId
                where a.StateCode == AccountState.Active                    
                select a).ToList();

注意:我最后删除了ToList()并且它不会抛出错误,但是当您尝试使用accounts对象时,它会再次抛出相同的错误。

错误

Microsoft.Xrm.Sdk.dll中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理。

附加信息:未将对象引用设置为对象的实例。

1 个答案:

答案 0 :(得分:2)

以下内容适合我,请将Linq替换为QueryExpression

var qe = new QueryExpression {EntityName = "account", ColumnSet = new ColumnSet()};
qe.ColumnSet.Columns.Add("name");

qe.LinkEntities.Add(new LinkEntity("account", "contractdetail", "accountid", "accountid", JoinOperator.Inner));
qe.LinkEntities[0].Columns.AddColumns("productid", "title");
qe.LinkEntities[0].EntityAlias = "contractdetails";

// Check Account State
FilterExpression accountState = qe.Criteria.AddFilter(LogicalOperator.And);
accountState.Conditions.Add(new ConditionExpression("statecode", ConditionOperator.Equal, 0));

FilterExpression productFilter = qe.LinkEntities[0].LinkCriteria.AddFilter(LogicalOperator.Or);
foreach (var product in products)
{
    var condition = new ConditionExpression
    {
        AttributeName = "productid",
        Operator = ConditionOperator.Equal
    };
    condition.Values.Add(product.ProductId);
    productFilter.Conditions.Add(condition); 
}                

EntityCollection resultsCollection = _OrgService.RetrieveMultiple(qe);

有关QueryExpression的详细信息,请查看以下链接。

  1. Retrieve multiple with the QueryExpression
  2. Use the ConditionExpression