简体   繁体   English

通过多个值查询字段的 Linq 语句转换为 in 语句

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

I've got a linq statement like this:我有这样的 linq 语句:

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

The statement when converted to sql looks like this:转换为 sql 时的语句如下所示:

 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.是否有人能够指出我正确的方向,以使转换后的 SQL 看起来像下面的示例。

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.我正在使用 C# ASP.Net MVC 5、EF6,但无论我尝试什么,都给出相同的结果并使用 IN 语句。

I use LINQPad4 with:我将 LINQPad4 用于:

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 IN vs OR 在这里讨论: 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.如果您的值是作为字符串请求和更新的,请评估您是否需要一个相关表来保存此值,并在您的表中具有一个具有整数值的相关 id。 This int column can have an index and this will provide better performance and a smaller footprint in your data and index size.这个 int 列可以有一个索引,这将提供更好的性能和更小的数据和索引大小的占用空间。

LINQ will try to provide the best execution based in your database structure. LINQ 将尝试根据您的数据库结构提供最佳执行。 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.因此,例如,如果您在数据库中提供了良好的设计,则在大多数情况下您不必担心 linq 查询的结果 sql 是什么。 (both in big querys and with big databases always make this check, and check the execution plan) (在大查询和大数据库中总是进行此检查,并检查执行计划)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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