反正我是否可以在Linq to Entities的 SQL Server中创建一个not in子句?
如果您使用内存中的集合作为过滤器,则最好使用Contains()的否定.请注意,如果列表太长,这可能会失败,在这种情况下,您将需要选择另一个策略(请参阅下面的使用策略进行完全面向数据库的查询).
var exceptionList = new List{ "exception1", "exception2" }; var query = myEntities.MyEntity .Select(e => e.Name) .Where(e => !exceptionList.Contains(e.Name));
如果您基于另一个数据库查询使用排除Except
可能是一个更好的选择.(这是LINQ to Entities中受支持的Set扩展的链接)
var exceptionList = myEntities.MyOtherEntity .Select(e => e.Name); var query = myEntities.MyEntity .Select(e => e.Name) .Except(exceptionList);
这假设一个复杂的实体,您根据另一个表的某些属性排除某些实体,并且需要未排除的实体的名称.如果您想要整个实体,那么您需要将异常构造为实体类的实例,以便它们满足默认的相等运算符(请参阅docs).
尝试:
from p in db.Products where !theBadCategories.Contains(p.Category) select p;
您要将哪个SQL查询转换为Linq查询?
我有以下扩展方法:
public static bool IsIn(this T keyObject, params T[] collection) { return collection.Contains(keyObject); } public static bool IsIn (this T keyObject, IEnumerable collection) { return collection.Contains(keyObject); } public static bool IsNotIn (this T keyObject, params T[] collection) { return keyObject.IsIn(collection) == false; } public static bool IsNotIn (this T keyObject, IEnumerable collection) { return keyObject.IsIn(collection) == false; }
用法:
var inclusionList = new List{ "inclusion1", "inclusion2" }; var query = myEntities.MyEntity .Select(e => e.Name) .Where(e => e.IsIn(inclusionList)); var exceptionList = new List { "exception1", "exception2" }; var query = myEntities.MyEntity .Select(e => e.Name) .Where(e => e.IsNotIn(exceptionList));
直接传递值时非常有用:
var query = myEntities.MyEntity .Select(e => e.Name) .Where(e => e.IsIn("inclusion1", "inclusion2")); var query = myEntities.MyEntity .Select(e => e.Name) .Where(e => e.IsNotIn("exception1", "exception2"));