问题描述
是否可以在查询中使用自定义方法例如:
Is it possible to use custom method In query for example:
var result = from u in context.MyTable where MyMethod(u) == 10 select u;
推荐答案
正如 Pranay 解释的那样,您不能将自定义 (C#) 方法作为 LINQ to SQL 查询的一部分,因为 LINQ to SQL 将无法查看在方法的表达式树中,因此它无法将其转换为 SQL.
As Pranay explains, you cannot have a custom (C#) method as part of the LINQ to SQL query, because LINQ to SQL wouldn't be able to look at the expression tree of the method and so it cannot translate it to SQL.
您拥有的一种选择是用 SQL 编写函数并将其作为 SQL 函数存储在 SQL Server 上(可能,您也可以使用 SQL CLR,但我还没有尝试过).然后您可以将该函数添加到您的 DataContext
类型,LINQ to SQL 会将其转换为对 SQL 服务器上的函数的调用.类似的东西:
One option that you have is to write your function in SQL and store it as a SQL function on the SQL Server (possibly, you could also use SQL CLR, but I have not tried that). Then you can add the function to your DataContext
type and LINQ to SQL will translate it to calls to the function on SQL server. Something like:
var result = from u in context.MyTable
where context.MyMethod(u) == 10 select u;
当然,问题是你需要用 SQL 编写函数(我认为 SQL CLR 也可以工作 - 但不确定性能和其他可能的并发症)
The problem, of course, is that you'll need to write the function in SQL (I think SQL CLR could also work - not sure about the performance and other possible complications though)
我还写了一篇文章(前段时间)展示了如何做到这一点当您将方法"编写为表达式树方式(作为 Expression
类型的值)时,这是可能的,因为在这种情况下,代码是编译为表达式树.但是,有一些后处理必须完成,您仍然可以只编写一个可以轻松内联到 LINQ 查询中的表达式.
I also wrote an article (some time ago) that shows how to do this when you write the "method" as an expression tree way (as a value of type Expression<Func<...>>
), which is possible, because in this case, the code is compiled as an expression tree. However, there is some postprocessing that has to be done and you can still write just a single expression that can be easily inlined in the LINQ query.
这篇关于LINQ to SQL 查询中的自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!