2

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Its. Working. Thanks. And one another thing... is there any option to change this query that I can receive all fields? Because in your query i received only name field.
Sure. Just remove the .Select(r => r.name) line and change the last line to .Select(x => Match.PrecentageMatching(x.name, pattern) > 0.5);.
2

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.

4 Comments

Good catch with the missing static, but that is not the problem here. The problem is that the EF data provider doesn't know how to translate Match.PercentageMatching into SQL code and will throw a runtime exception.
@DanielHilgarth didn't know that. sheepish I just use the basic stuff. Voted your answer.
Yes. Daniel is right. This will compile but will not work. You will get an exception: "LINQ to Entities does not recognize the method 'Int32 LevensteinDistance(System.String, System.String)' method, and this method cannot be translated into a store expression."
@Daryl: That's what we are here for :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.