[英]Asp.Net - Unable to create a constant value of type. Only primitive types or enumeration types are supported in this context
[英]LINQ Query error: Unable to create a constant value of type. Only primitive types or enumeration types are supported in this context
我有一个对象列表,其中包含已从较大列表中过滤掉的合同信息List<Contract> endedContracts
。 我现在正在尝试将该列表中的信息与数据库中的记录进行匹配,并添加一些其他过滤器。
var endedContracts = _contracts
.Where(x => x.Contract.IsContractInLastBillingPeriod(referencePeriod))
.Where(x => x.Contract.IsContractCoveredByLiveInvoices(x.Contract.Invoices)).ToList();
当我运行以下查询时,我得到了错误。
var crystallisedCommissions = _context.Contracts
.Where(x => x.Statement.Sent)
.Where(x => x.Statement.Broker == endedContracts.First().Broker.Code)
.Where(x => !Period.IsPeriodBeforeReferencePeriod(x.Statement.Period, CUT_OFF_PERIOD))
.Where(x => endedContracts.Any(y => y.Contract.Identifier == x.Identifier
&& y.Contract.StartDate == x.ContractStartDate
&& y.Contract.EndDate == x.ContractEndDate)).ToList();
确切的错误:
无法创建“合同”类型的常量值。 在这种情况下,仅支持原始类型或枚举类型。”
endedContracts
是一个内存中列表,不能直接在此查询中使用。 而是在查询之外获取所需的值,例如:
//Get the code here
var brokerCode = endedContracts.First().Broker.Code;
var crystallisedCommissions = _context.Contracts
.Where(x => x.Statement.Sent)
.Where(x => x.Statement.Broker == brokerCode) //Use the code here
.Where(x => !Period.IsPeriodBeforeReferencePeriod(x.Statement.Period, CUT_OFF_PERIOD))
.Where(x => endedContracts.Any(y => y.Contract.Identifier == x.Identifier
&& y.Contract.StartDate == x.ContractStartDate
&& y.Contract.EndDate == x.ContractEndDate)).ToList();
注意, endedContracts
是内存中的集合,并且linq将被转换为sql,该sql将在数据库服务中执行Entity Framework无法将整个数据集合上载到数据库,因此在执行查询时,没有endedContracts
。
因此,您有2个选项可以使其起作用:
让endedContracts
是一个查询对象(IQueryable)而不是执行它( ToList()
),则整个查询将在数据库服务中转换和执行。
执行查询以检索两个数据集并执行内存中的linq(这可能是一个严重的性能问题)。
结论,两个数据集的迭代必须在同一台计算机,.NET应用程序或数据库中进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.