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

Linq predicate query results is not working for further Linq Join

我正在使用 Predicate 查询的结果在 Linq 查询中编写连接。但它抛出以下错误。然而,当我在运行中进行类似查询时,SQL却得到了returns预期的结果。

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() 并且它不会抛出错误,但是当您尝试使用帐户对象时它会抛出相同的错误再次出错。

错误

'System.NullReferenceException' 类型的异常发生在 Microsoft.Xrm.Sdk.dll 中,但未在用户代码中处理。

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

以下对我来说非常有用,将 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