【问题标题】:LINQ Query error: Unable to create a constant value of type. Only primitive types or enumeration types are supported in this contextLINQ 查询错误:无法创建类型的常量值。此上下文仅支持原始类型或枚举类型
【发布时间】:2019-05-16 09:33:01
【问题描述】:

我有一个对象列表,其中包含已从较大列表中过滤掉的合同信息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();

确切的错误:

无法创建“合同”类型的常量值。此上下文仅支持原始类型或枚举类型。”

【问题讨论】:

    标签: c# entity-framework linq


    【解决方案1】:

    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();
    

    【讨论】:

      【解决方案2】:

      注意endedContracts 是内存中的一个集合,linq 将被转换为将在数据库服务中执行的 sql Entity Framework 无法将整个数据集合上传到数据库,所以在执行查询时,没有endedContracts

      因此,您有 2 个选项可以让它工作:

      1. endedContracts 成为查询对象 (IQueryable) 而不是执行它 (ToList()),然后整个查询将在数据库服务中被翻译和执行。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多