LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)' method

I’ve been dabbling with the ADO.NET Entity Framework in .NET 3.5, was trying to convert this SQL WHERE clause, which uses the LIKE operator, into LINQ syntax:

String strWhereClause = String.Format(CultureInfo.CurrentCulture, "Type={0} AND Name LIKE '*{0}*'", orgType, orgName);

I read somewhere which suggested to use the SqlMethods helper class. So I tried:

var objQuery = repository.Organization.Where(vendor => vendor.Type == orgType && SqlMethods.Like(vendor.Name, "”%” + orgName + “%”));

The query is targeting an Organization table. repository is an instance of an ObjectContext subclass which has been  auto generated by Visual Studio’s ADO.NET Entity Data Model wizard.  orgType and orgName are passed-in parameters.

The above approach resulted in the following runtime error (notice the redundant occurrence of the word ‘method’ in the error message):

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

I then saw a post on stackoverflow which suggested to use Contains(), StartsWith(), or EndsWith() to mimick the LIKE operator. So I tried:

var objQuery = repository.Organization.Where(vendor => vendor.Type == orgType && vendor.Name.Contains(orgName));

This works, but if orgName.Length is zero, then the query returns zero rows.  So finally, a slight mod to the above query achieved the desired effect:

var objQuery = repository.Organization.Where(vendor => vendor.Type == orgType && (orgName.Length == 0 || vendor.Name.Contains(orgName)));

28 comments:

th2tran said...

Trackback: http://stackoverflow.com/questions/1033007/like-operator-in-entity-framework/1161919

Thomas Hansen said...

I have found a workaround to make LINQ accept the StartsWith command..

IEnumerable query = context.PEOPLE;

query = query.Where(a => a.FULL_NAME.StartsWith(authorSearchName, StringComparison.OrdinalIgnoreCase)).Take(50).OrderBy(a => a.FULL_NAME);

The secret is NOT to work on the context.PEOPLE object directly but to create a temporary variable (query) and make the LINQ on this..

regards

Unknown said...
This comment has been removed by the author.
Unknown said...

Doesn't '.contains' produce a SQL 'IN'. If you had a complete value you should have never been looking for an equivalent to 'LIKE' because its inefficient. Only use 'LIKE' when you only have a partial value.

Rohan said...

In the event that you are confronting issue with Binance account? Simply call Binance Support Number +1 (856) 462-1192 phone Number and fix all issues.+1 (856) 4 6 2-1 1 9 2 Binance Support Phone Number. While overseeing the cryptographic cash you may go up against a couple of issues in the exchange or trade, on the grounds that of some kind of complexities of the working of this trade module ,there might be some deferment in withdrawal or move. for more information visit here: https://www.thecustomercentre.com/webexchanges/binance-support-number/

Rohan said...

Any Error In blockchain Wallet call us?
Do you realize the procedure to determine the forthcoming blunder which happens while making a store in your Blockchain account through-checked ace card? What might be the inception for such issues and do you need proficient help? So as to dispose of such issues and to benefit the most ideal answers , you can approach Blockchain support number +1 (856) 462-1192 which is the way to get interface with the group which is working during the time for help. more info visit here: https://www.thecustomercentre.com/webexchanges/blockchain-support-number/

Rohan said...

In case you are defying a couple of issues with Coinbase?
Contact Coinbase Support Number +1-(856)-462-1192 Phone Number and resolve all your coinbase record issues. In case you are going up against a couple of issues with Coinbase? Contact Coinbase Support Number +1-(856) 462-1192 Phone Number and resolve all your coinbase record issues. hop to Main Content. for more data visit here: https://www.thecustomercentre.com/webexchanges/coinbase-support-number/

Prathima Hospitals said...

Your blog inspires me every time when I read it. I love reading blogs. I don't excite always by reading blog posts. But in your blog I find something that implies in blogging.
best hospital in Hyderabad

Settle Via us said...

Very nice post I really enjoyed it...You can also visit my website for.
Student Visa Australia

Sai Sudha Hospital said...

Awesome post appreciates your efforts and really enjoyed the style of your writing. https://mothertobe.in/

Technical Service provider said...

Wow, I'm very impressed with the words, and it looks very good. All blog which you write has a knowledgeable content and many beginers learn many things from your writing. As I aslo write blog in which we provide information and services for any type of problem related to Norton Antivirus. If you face any type of problem related to Norton Antivirus you can use norton.com/setup download or can visit our website.

Steve Paul said...

Not Able To Receive Bitcoin From Other Wallets

Bitcoin is the most popular to trade in Gemini exchange and sometime susers error receiving bitcoin from other wallets in Gemini wallet. Gemini wallet is compatible on all devices such as desktop, ios, and android. If you are unable to deal with this error and looking for solution to handle all troubles, you can always call on Gemini helpdesk number which is functional always for guidance. Reach the team to get quality results that would surely help in eliminating all kind of problems in no time. Speak to the team always and get verified results to deal with such issues.

Gemini customer care

Crypto Support said...

Bitcoin Support telephone number For

Are you a Bitcoin +1-888-670-6949 user United Nations agency is facing problems associated with transactions? Transactions in Bitcoin area unit typically a swish ride however generally folks ought to wait and it may be annoying. Dial Bitcoin Support Phone Number +(1-888) 6 7 0 - 6 9 4 9 if you wish to eliminate this issue. The representative at Bitcoin exchange provides seamless resolution to every and each drawback of your and facilitate perceive step by step method simply.Visit our site:- https://www.cryptocurrencyphonesupport.com/bitcoin-customer-support-phone-number/

wellness said...
This comment has been removed by the author.
wellness said...

Best Orthopedic Hospital in Hyderabad,Orthopaedics Surgery is a specialty dealing with the musculoskeletal problems of all age groups from newborns to seniors. Sreemanju hospitals provides comprehensive orthopaedic services with patient-centric, individualized care. A dedicated team of skilled orthopaedic surgeons supported by a multidisciplinary team of neurosurgeons, plastic and vascular surgeons, physiotherapists, anaesthetists, intensivists provide services round-the-clock. We provide standardized care for best results in the areas of Trauma & Emergency, Total Joint Replacements, Arthroscopy & Sports Injuries, Paediatric Orthopaedics, and Spine Surgeries.
Best Orthopedic Hospital in Hyderabad

abrhospital said...

Thank You
ABR Neuro Multi Specialty Hospitals General Physician Uppal The range of diseases managed by the Department includes – general sickness to the management of chronic and complex diseases. Some of the services rendered at the Department are given Primary care,
General Physician Uppal

Chavan Hospital said...

This is very helpful blog , thank for your helpful information.
Gynecologist Hospital In Hyderabad

sreemanju hospital said...

thanks for sharing information it's Very nice post I really very good bloge

Best General Surgery specialist in KPHB the General Surgery department at Sree Manju Hospitals genenal surgeory doctor are deals with pateints and any of their surgical needs,Surgeons at Sree Manju Hospitals

Best General Surgery specialist in KPHB

sreemanju hospital said...
This comment has been removed by the author.
sreemanju hospital said...
This comment has been removed by the author.
Best Hospital in Hyderabad said...

Thanks you

Sreemanju Hospital is one of the Best Hospital in Hyderabad is one among the Best Multispecialty Hospitals in Hyderabad, Sree Manju Hospitals was among the first few hospitals in the city to leverage technology to facilitate seamless healthcare delivery.
Sremanju hospital is the best super speciality hospital in Hyderabad It has set up an advanced technological base for various types of medical and surgical treatments and diagnostic units, in order to provide efficient medical care for patient welfare
Specialized departmental intensive care units with ultra sophisticated medical equipment, High-tech equipment available for monitoring purposes at various departments for diagnostic purposes & treatments

Best Hospital in Hyderabad

sreemanju hospital said...

Thanks for sharing information...

sreemanju hospital is the Best Orthopedic Hospital in Hyderabad, We have well-experienced doctors and surgeons who are adept at offering the right diagnosis, surgery – both invasive and minimally-invasive ones – as well as treatments. The Institute of Orthopedics and joint replacement at Sreemanju hospital.
We offer the best orthopedic treatment, complex orthopedic surgeries, and complete relief for bone and joint problems. we have a few of the top orthopedic doctors in the city. They offer treatments like medications, hormone treatments, especially for women, physical therapy and exercises, and the right nutrition
The orthopedic team diagnoses, operates and treats problems affecting the bones, joints and muscles of patients in all age groups. one of the best orthopedic treatments with efficient and painless methods. Our center of excellence is open 24/7 with an expert doctor in the unit all the time.
Best Orthopedic Hospital in Hyderabad

abrhospital said...

Thank You
ABR Hospital Nero Multispeciality Hospital General Medicine In Uppal General medicine is the very basic requirement of any healthcare organization and its practitioners promote general disease prevention methods and champion a healthy society. The Department of General Medicine at ABR NEURO Multi SPECIALTY HOSPITAL In Hyderabad
General Medicine in Uppla

Hiee said...
This comment has been removed by the author.
Chavan Hospital said...
This comment has been removed by the author.
Chavan Hospital said...

Thank you
Chavan Hospital, Hyderabad are just a 10min distance away from the airport have a great scope for serving National and International patients. Chavan Hospitral is Renowed as one of the Hospital In Hyderabad. Our Chavan Hospital comprehensive range of treatment services supported by department offer accurate diagnosis and treatment to the patients on in-patinet, out-patinet, daycare and emergency basis. In a very short span of time, we are established as the most trusted hospital in Hyderabad through its centres of excellence, departments, and outpatient clinics equipped with cutting-edge technology and the most advanced equipment for performing complex surgeries. From pediatric to geriatric, we are one-stop solution for patients of all ages.https://www.chavanhospitals.co.in/

Chavan Hospitals said...

Thanks for sharing infermation
If You are searching for the best hospital In Hyderabad? Then Chavan Hospital is one of the leading Multispeciality Hospitals in Hyderabad, Our hospital provides top-notch quality diagnostic services and best-in-class treatments. Our physicians are specialized and experienced in Oncology, Nephrology, Gynaecology, General Surgery, Cardiology, etc. Chavan Hospital offered a wide team of adept and responsible doctors and physicians, striving relentlessly to provide modern healthcare facilities for a healthier generation.
https://www.chavanhospitals.co.in/about

basha007 said...

Sree manju hospital is one of the Best Hospital in KPHB
, Kukatpally to provide world class facilities, and providing the best treatments with the most experienced and specialised doctors with highly advanced technology.