Linq到SQL-自定义功能[英] LINQ to SQL - custom function

本文是小编为大家收集整理的关于Linq到SQL-自定义功能的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我想运行这样的linq查询:

var words = from p in db.Words
   where p.Document.Corpus.Name == corpus
   //where LevenshteinDistance(p.Text.ToCharArray(), word.ToCharArray()) < threshold
   select p;

但是,如果我将" LevenShteIndistance"功能放置在其中,它将产生错误:

notsupportedException:方法'char [] tochararray()'没有支持转换为SQL.

有正确的方法吗?

推荐答案

linq至SQL试图将整个表达式转换为SQL.如果要在SQL Server上运行距离函数,则需要定义SQL Server UDF并将自定义CLR方法映射到此.如果您满足于获取所有结果,然后在距离函数上过滤客户端,请使用AseNumerable():

var words = (from p in db.Words
             where p.Document.Corpus.Name == corpus)
             select p)
            .AsEnumerable()
            .Where(p => /* distance function */ < threshold);

可触及的力linq for sql列举查询结果,允许使用linq to对象和您的距离委派解决查询的其余部分(而不是被翻译成SQL).

).

本文地址:https://www.itbaoku.cn/post/1557108.html

问题描述

I would like to run a LINQ query like this:

var words = from p in db.Words
   where p.Document.Corpus.Name == corpus
   //where LevenshteinDistance(p.Text.ToCharArray(), word.ToCharArray()) < threshold
   select p;

But if I place the "LevenshteinDistance" function in there it will generate an error:

NotSupportedException: Method 'Char[] ToCharArray()' has no supported translation to SQL.

Is there a correct way to do this?

推荐答案

LINQ to SQL tries to translate the entire expression into SQL. If you want to run your distance function on SQL Server, you'll need to define a SQL Server UDF and map a custom CLR method to that. If you're content to get all the results and then filter client-side on the distance function, use AsEnumerable():

var words = (from p in db.Words
             where p.Document.Corpus.Name == corpus)
             select p)
            .AsEnumerable()
            .Where(p => /* distance function */ < threshold);

The AsEnumerable forces LINQ to SQL to enumerate the query results, allowing the remainder of the query to be resolved using LINQ to Objects and your distance delegate (instead of being translated to SQL).