Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ查询错误:无法创建类型为的常量值。在此上下文中仅支持基元类型或枚举类型_C#_Entity Framework_Linq - Fatal编程技术网

C# LINQ查询错误:无法创建类型为的常量值。在此上下文中仅支持基元类型或枚举类型

C# LINQ查询错误:无法创建类型为的常量值。在此上下文中仅支持基元类型或枚举类型,c#,entity-framework,linq,C#,Entity Framework,Linq,我有一个对象列表,其中包含已从较大列表中筛选出来的合同信息list-endedContracts。我现在正试图通过一些进一步的过滤器将此列表中的信息与数据库中的记录进行匹配 var endedContracts = _contracts .Where(x => x.Contract.IsContractInLastBillingPeriod(referencePeriod)) .Where(x => x.Contract.IsContractCoveredByLive

我有一个对象列表,其中包含已从较大列表中筛选出来的合同信息
list-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将在数据库服务中执行 实体框架无法将整个数据集合上载到数据库,因此在执行查询时,没有
endedContracts

因此,您有两个选项可以使其工作:

  • endedContracts
    成为一个查询对象(IQueryable),而不是执行它(
    ToList()
    ),那么整个查询将在数据库服务中翻译和执行

  • 执行查询以检索两个数据集并在内存中执行linq(这可能是一个严重的性能问题)

  • 结论:两个数据集的迭代必须在同一台机器、.NET应用程序或数据库中进行