简体   繁体   English

SQL Server IN子句的实体框架核心

[英]Entity Framework Core to SQL Server IN Clause

We are converting from LINQ to SQL to Entity Framework Core 2.2 and are finding that the translation of Contains operations do not become IN clauses in SQL Server. 我们正在从LINQ转换为SQL到Entity Framework Core 2.2,并且发现Contains操作的转换不会成为SQL Server中的IN子句。 What is happening is that EFCore is pulling back all of the data using the other conditions and then filtering it down locally. 发生的事情是EFCore正在使用其他条件撤回所有数据,然后在本地过滤掉它。 This is not acceptable. 这是不可接受的。 We can use EF.Functions.Contains but this requires us to enable Full Text Search in SQL Server, which is over kill. 我们可以使用EF.Functions.Contains,但这要求我们在SQL Server中启用全文搜索,这是过度杀戮。

Any idea how to get a statement like the following to translate to an IN clause in SQL Server? 任何想法如何获得如下的语句转换为SQL Server中的IN子句?

var myValues = new [] { 1, 2, 3, 4, 5 };
var qry = _context.Table.Where(t => myValues.Contains(t.TableProperty));

Okay, maybe I over simplified the code to keep it simple for the question. 好吧,也许我过度简化了代码以使问题变得简单。 The actual code looks like: 实际代码如下:

    voterQuery = voterQuery.Where(v => voterFilter.VoterStatus.Select(p => p.Value).Contains(v.VotStatus.ToString()));

What is happening in our code is that we are building up an IQueriable from user selections on a filtering screen. 我们的代码中发生的是我们正在通过过滤屏幕上的用户选择构建IQueriable。 voterFilters contains a collection of these selection criteria. voterFilters包含这些选择标准的集合。 VoterStatus is one of the selection criteria which is a List, which are from a winforms CheckedListItems control. VoterStatus是List的选择标准之一,它来自winforms的CheckedListItems控件。 The selection of p.Value returns a List of strings. p.Value的选择返回字符串列表。 I have tried to project the list of strings to an array, with the same results of the IN clause not being created or a server query. 我试图将字符串列表投影到一个数组,其中没有创建IN子句的相同结果或服务器查询。 Perhaps, EFCore does not allow strings to be used for the IN clause values. 也许,EFCore不允许字符串用于IN子句值。 Any insight would be appreciated. 任何见解将不胜感激。

Currently (as of v2.2.3), EF Core requires the expression used for Contains to be a simple IEnumerable<T> variable (no LINQ operators) where the T is primitive type. 目前(从v2.2.3开始),EF Core要求用于Contains的表达式是一个简单的IEnumerable<T>变量(没有LINQ运算符),其中T是原始类型。

Which means you need to move the voterFilter.VoterStatus.Select(p => p.Value) into variable outside the query expression tree and use that variable inside: 这意味着您需要将voterFilter.VoterStatus.Select(p => p.Value)到查询表达式树之外的变量中并使用该变量:

var voterStatusFilter = voterFilter.VoterStatus.Select(p => p.Value);
voterQuery = voterQuery.Where(v => voteStatusFilter.Contains(v.VotStatus.ToString()));

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

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