有没有机会在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
过滤返回的数据,则会遇到问题,因为首先需要返回所有数据并在客户端上过滤数据。如果表很大,这可能是个问题。关于c# - 在LINQ查询中调用C#方法( Entity Framework ),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7495890/