在linq查询中调用c#方法(实体框架)

nos*_*bor 2 .net c# sql linq entity-framework

有没有机会在linq查询中运行c#方法?我需要做那样的事情:

//...
class Match {
  public double PrecentageMatching(string s1, string s2) {
    //...
    return result; // value from 0.0 to 1.0
  }
}
//...

string pattern = "nameOfRecord";
var similarRecords = db.Table.Select( 
   r => Match.PrecentageMatching(r.name, pattern) > 0.5 
);
Run Code Online (Sandbox Code Playgroud)

我知道linq不会知道PrecentageMatching方法.但我想知道是否有办法做到这一点?

我正在使用Entity框架.我需要在数据库端没有存储过程和程序集的情况下执行此操作.我没有访问数据库.

Dan*_*rth 5

首先需要从数据库中获取数据,然后才执行转换:

string pattern = "nameOfRecord";
var similarRecords = db.Table
                       .Select(r => r.name)
                       .ToList() // This call fetches the data from the DB
                       .Select(x => Match.PrecentageMatching(x, pattern) > 0.5);
Run Code Online (Sandbox Code Playgroud)

这根本不是问题,因为您只是使用您的方法转换返回的数据.如果要使用您的方法过滤使用的返回数据Where,则会出现问题,因为您首先需要返回所有数据并过滤客户端上的数据.如果表很大,这可能是一个问题.