Contains a method for comparing a string array in C #

I want to compare the sting field with a string array using LINQ, Ive written the following extension method for comparison, but it does not work correctly.

public static bool Contains(this string source, string[] keys) { foreach (var item in keys) { if (source.Contains(item)) return true; } return false; } 

And this is my request:

 string[] keys = key.Split('+'); var pages = context.Pages.Where(x => x.Title.Contains(keys)); 

Error received by ive:

LINQ to Entities does not recognize the 'Boolean Contains (method System.String, System.String [])' method, and this method cannot be translated into a storage expression.

+4
source share
3 answers

You cannot use your own methods in LINQ like this, but you can avoid overwriting with the usual LINQ statements:

 string[] keys = key.Split('+'); var pages = context.Pages.Where(x => keys.Any(key => x.Title.Contains(key))); 

If this does not work, I suspect that it is almost impossible in EF.

+7
source

The lambda expression that you write inside Where is actually evaluated and translated into SQL using EF. For example, when you write

 db.Pages.Where(x => x.Title == "Hello") 

EF knows how to convert the resulting IQueryable<T> to something like:

 SELECT ... FROM Pages WHERE title = 'Hello' 

Similarly, he knows about some common methods and operators, for example:

 db.Pages.Where(x => x.Contains("Hello")) 

EF knows to translate String.Contains to:

 SELECT ... FROM Pages WHERE title LIKE '%Hello%' 

However, when you use your own methods with an expression, EF does not know how to translate this custom method into SQL, which it complains about in the error message you saw.

+5
source

LINQ to Entities does not recognize the 'Boolean Contains (System.String, System.String [])' method, and this method cannot be translated into a storage expression.

See how your code translates to SQL, and if I'm not mistaken, your error says ' Boolean Contains (System.String, This method cannot be translated. This means that this particular section is not able to convert itself to SQL if you draw your line as BIT, it might work.Okay, if someone feels that I may be in the wrong direction, please let me know.

+1
source

Source: https://habr.com/ru/post/1497060/


All Articles