简体   繁体   中英

Linq statement that queries field by multiple values gets converted to in statement

I've got a linq statement like this:

this.DataContext.TableName.Where(r => r.Field =="REQUEST" || r.Field== "UPDATE")

The statement when converted to sql looks like this:

 WHERE ([Extent1].[Field] IN (N'REQUEST',N'UPDATE'))

rather than:

WHERE Field = 'REQUEST' or Field = 'UPDATE'

The bottom example runs twice as fast as the top. Is anyone able to point me in the right direction in order to get the converted SQL to look like the below example.

I'm using C# ASP.Net MVC 5, EF6, but whatever I seem to try just gives the same results and uses the IN statement.

I use LINQPad4 with:

Customers.Where(x => x.Name == "Tom" || x.Name == "Dick").Dump()

Generate:

-- Region Parameters
DECLARE @p0 NVarChar(1000) = 'Tom'
DECLARE @p1 NVarChar(1000) = 'Dick'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [Customer] AS [t0]
WHERE ([t0].[Name] = @p0) OR ([t0].[Name] = @p1)

IN vs OR is discussed here: IN vs OR in the SQL WHERE Clause

Hope this helps.

In this case if the concern is performance well, you have a big long list of articles to read to have your own opinion. For once maybe you have to concern about if your column needs and index and if your statistics are updated.

If your values are request and update as a string, evaluate if you need a related table to hold this values and have a related id in your table with an integer value. This int column can have an index and this will provide better performance and a smaller footprint in your data and index size.

LINQ will try to provide the best execution based in your database structure. So for instance if you provide a good design in your database you dont have to bother in most cases of what is the result sql from the linq query. (both in big querys and with big databases always make this check, and check the execution plan)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM