簡體   English   中英

LINQ查詢錯誤:無法創建類型的常量值。 在此上下文中僅支持原始類型或枚舉類型

[英]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個選項可以使其起作用:

  1. endedContracts是一個查詢對象(IQueryable)而不是執行它( ToList() ),則整個查詢將在數據庫服務中轉換和執行。

  2. 執行查詢以檢索兩個數據集並執行內存中的linq(這可能是一個嚴重的性能問題)。

結論,兩個數據集的迭代必須在同一台計算機,.NET應用程序或數據庫中進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM