Linq To Entities: String.Contains a list

c# entity-framework-core linq pomelo-entityframeworkcore-mysql

Question

I am using ASP.net Core 3.0 with Entity Framework Core 3.0 and Pomelo.EntityFrameworkCore provider for MySQL, I need to query all the users that are from specific Towns. Lets say for example I have a list of strings called targettedTowns in which I have the following towns

var targettedTowns = new List<string>() {"korangi","landhi","zia colony","shah faisal","quaidabad"};
  • korangi
  • landhi
  • zia colony
  • shah faisal
  • quaidabad

Now I want to find all the users that are located in the targettedTowns list using Linq Lambda syntax.

Users in my database have their towns saved like

  • Korangi
  • Korangi-Zia Colony
  • Korangi-Bhittai Colony
  • Korangi-Allah Wala Town
  • Landhi-Sherpao
  • Landhi-Awami Colony
  • Landhi-Sherabad
  • ShahFaisal

What I am trying currently is

var users = context.Users.Where(x => x.Town.ToLower().Contains(targettedList)).ToList();

but as String.Contains does not take a list in argument so I cant use this.

1
0
3/29/2020 1:27:32 PM

Accepted Answer

You can try using Any method, I'm not sure whether it's supported but it's worth trying:

var result = context.Data.Where(data => searchTerms.Any(x => data.Name.Contains(x)) ||
                                        searchTerms.Any(x => data.Code.Contains(x));

If this gives you NotSupportedException you can add AsEnumerable before Where to fetch all records and execute the query in memory rather than DB.

13
12/4/2014 1:54:59 PM

Popular Answer

I'm late to the party but using the SearchExtensions nuget package you could do something like the following

var result = context.Data.Search(x => x.Name, x => x.Code).Containing(searchTerms);

This builds an expression tree so will still perform the query on the server (and not in memory) and will essentially run the SQL you desire above



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow