繁体   English   中英

在LINQ查询中调用C#方法(实体框架)

[英]Call c# method in linq query(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 
);

我知道那里linq不会知道PrecentageMatching方法。 但是我想知道是否有任何办法可以做到?

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

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

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);

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

将您的PrecentageMatching方法更改为静态方法。 然后它将能够找到Match.PrecentageMatching方法。

另外,您在此处执行的操作将返回IEnumerable布尔值。 如果要从表中返回记录,则需要“位置”而不是“选择”。

编辑:根据注释,您需要调用ToList()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM