LINQ to SQL 查询中的自定义方法

Custom Method in LINQ to SQL query(LINQ to SQL 查询中的自定义方法)
本文介绍了LINQ to SQL 查询中的自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

是否可以在查询中使用自定义方法例如:

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 查询中的自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

LINQ to SQL query using quot;NOT INquot;(使用“NOT IN的 LINQ to SQL 查询)
How to do a full outer join in Linq?(如何在 Linq 中进行完整的外部联接?)
LINQ to SQL Web Application Best Practices(LINQ to SQL Web 应用程序最佳实践)
How do I group data in an ASP.NET MVC View?(如何在 ASP.NET MVC 视图中对数据进行分组?)
how to update the multiple rows at a time using linq to sql?(如何使用 linq to sql 一次更新多行?)
how to recognize similar words with difference in spelling(如何识别拼写不同的相似词)