EntityFramework 4.0:方法无法转换为商店表达式

时间:2011-09-14 15:32:58

标签: c# linq entity-framework

我有一段客户为IQueryable<Customer>

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

当我跑步时,我收到错误Method cannot be translated into a store expression。现在我知道我需要使用EntityFunctions(即EF的Canonical函数),但当我在EntityFunctions中检查列表时,没有可用于将字符串转换为整数的方法。

注意:我知道如果我对对象执行Linq,即在IQueryable上执行ToList()然后进行过滤,它将全部起作用。但是我不想那样做,因为这会降低我的性能,因为Customers表的行数太大了。此外,无法将我的数据库字段转换为int。

更新:我正在使用Sql Server 2008.只是包含它,如果它可以提供任何帮助。

UPDATE2: 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]

1 个答案:

答案 0 :(得分:3)

如果所有字符串值都是有效整数

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