开发者

Call c# method in linq query(entity framework)

Is there any chance to run c# method in linq query? I need to do something like that:

//...
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 
);
开发者_运维问答

I know that there linq wont know a method PrecentageMatching. But I'm wonder if there is any way to do it?

I'm using Entity framework. I need to do it without stored procedures and assembly on database side. I dont have access to database.


You first need to fetch the data from the database and only then perform the transformation:

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

That's not a problem at all, because you are only transforming the returned data with your method. If you want to use your method to filter the returned data using Where, you have a problem, because you would first need to return ALL data and filter the data on your client. This might be a problem if the table is big.


Change your PrecentageMatching method to a static method. It will then be able to find Match.PrecentageMatching method.

Also, what you're doing there will return a IEnumerable of boolean values. If you want to return records from the Table, you want "Where" instead of "Select".

Edit: as per comments, you need to call ToList() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜