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

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

我正在使用谓词查询的结果在 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(),它不会抛出错误,但是当您尝试使用帐户对象时,它会再次抛出相同的错误。

错误

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

其他信息:对象引用未设置到对象的实例。

最佳答案

以下内容非常适合我,将 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

关于c# - Linq 谓词查询结果不适用于进一步的 Linq Join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30799624/

相关文章:

asp.net - GetAll 或 GetList 函数和性能问题

c# - 如何防止 Microsoft Dynamics CRM 2011 中没有 ExecutionContext.CallerOrigin 的无限循环?

c# - 从 MemoryStream 加载 HtmlDocument

c# - Mega-man 2 相机帮助 (Unity)

c# - 在 HTML 报告字段中显示尾随空格

c# - Resharper 在返回前停止换行

sql - 如何更改 linq-to-entities 生成的 sql?

c# - 优化Linq Where,使用key

javascript - 如何在 MS CRM 2011 中获取字段类型

sql-server - Microsoft Dynamics CRM 还是 SQL Server?