gpt4 book ai didi

c# - Entity Framework 4.0 : Method cannot be translated into a store expression

转载 作者:行者123 更新时间:2023-11-30 12:15:26 24 4
gpt4 key购买 nike

我有这段代码,其中 Customers 是 IQueryable<Customer>

Customers = Customers.Where ( C => Int32.Parse(C.Salary) > 5000);

当我运行时出现错误 Method cannot be translated into a store expression .现在我知道我需要为此使用 EntityFunctions(即 EF 的规范函数),但是当我检查 EntityFunctions 中的列表时,没有可用于将字符串转换为整数的方法。

注意:我知道如果我对对象执行 Linq,即在 IQueryable 上执行 ToList(),然后进行过滤,一切都可以。但我不想这样做,因为这会降低我的性能,因为 Customers 表的行数太大。也无法将我的数据库字段转换为 int。

更新:我正在使用 Sql Server 2008。如果它有任何帮助,我会考虑包含它。

更新 2: Aducci 在他的回答中提供了一个真正巧妙而巧妙的解决方案。但是从中生成的Sql非常难看。例如:

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM ( SELECT
[Project2].[C1] AS [C1],
(SELECT TOP (1) [top].[C1] AS [C1]
FROM ( SELECT TOP (1)
CAST( [Project2].[PostalCode] AS int) AS [C1]
FROM [dbo].[Customers] AS [c]
) AS [top]) AS [C2]
FROM ( SELECT
[Extent1].[PostalCode] AS [PostalCode],
(SELECT TOP (1) [top].[C1] AS [C1]
FROM ( SELECT TOP (1)
CAST( [Extent1].[PostalCode] AS int) AS [C1]
FROM [dbo].[Customers] AS [c]
) AS [top]) AS [C1]
FROM [dbo].[Customers] AS [Extent1]
) AS [Project2]
) AS [Project4]
WHERE (CASE WHEN ([Project4].[C1] IS NULL) THEN 0 ELSE [Project4].[C2] END) > 5000
) AS [GroupBy1]

唯一的区别是它使用邮政编码而不是薪水。如果您不是真的很担心这个丑陋的 Sql,您当然可以使用,但如果您是,那么我在我的评论中提供了 1 个链接,它以非常好的和高效的方式工作。

这是我提到的链接生成的等效 Sql:

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [dbo].[Customers] AS [Extent1]
WHERE CAST( CAST( [Extent1].[PostalCode] AS int) AS float) > cast(5000 as float(53))
) AS [GroupBy1]

最佳答案

如果所有字符串值都是有效整数,这将起作用

var query = from c in Customers
let salaryInt = Customers.Take(1).Select(x => c.Salary).Cast<int>().FirstOrDefault()
where salaryInt > 5000
select c;

关于c# - Entity Framework 4.0 : Method cannot be translated into a store expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7419019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com