自定义的方法在LINQ to SQL查询 [英] Custom Method in LINQ to SQL query

查看:199
本文介绍了自定义的方法在LINQ to SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  VAR的结果=从u在context.MyTable那里的MyMethod(U)== 10选择U;


解决方案

由于Pranay解释说,你不能有一个自定义(C#)方法作为SQL查询的LINQ的一部分,因为LINQ到SQL就没法看在方法的前pression树,所以无法将其转换为SQL。

这是你必须是写你的函数在SQL中,并将其存储作为SQL Server(可能的话,你也可以使用SQL CLR,但我没有试过)上的SQL函数的一种选择。然后您可以将功能添加到您的的DataContext 键入和LINQ to SQL将它翻译成调用SQL服务器上的功能。是这样的:

  VAR的结果=从u在context.MyTable
             其中,context.MyMethod(U)== 10选择U;

问题当然是,你需要编写SQL中的功能(我认为SQL CLR也可以工作 - 不知道有关性能和其他可能的并发症虽然)

我也写了一篇文章(前一段时间),显示如何做到这一点当你写的法作为一名前pression树的方式(如键入防爆pression℃的值; Func键< ...>> ),这是可能的,因为在这种情况下,code为编译为一个前pression树。然而,有一个必须做了一些后期处理,你仍然可以写只是一个单一的前pression可以在LINQ查询很容易地内联。

Is it possible to use custom method In query for example:

var result = from u in context.MyTable where MyMethod(u) == 10 select u;

解决方案

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.

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; 

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)

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查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆