如果用in是字符串类型无问题,可以直接这样用
var result = SNFService.Instance.ModuleService.GetList(UserInfo).Where(entity => entity.DeletionStateCode == 0 ).Where(entity => urls.Contains((entity.NavigateUrl == null ? "" : entity.NavigateUrl).ToLower())).OrderBy(entity => entity.SortCode).ToList();
如果是数值类型需要按如下处理:
熟悉LINQ的朋友也许会碰到标题的问题,且很自然地想起使用下面地语句实现:
IList<int> ids = new List<int> { 2, 3, 4 };
var list = context.TestTables.Where(a => ids.Contains(a.RID)).ToList();
var list = context.TestTables.Where(a => ids.Contains(a.RID)).ToList();
然而,运行发现系统会抛出如下异常:
LINQ to Entities 不识别方法“Boolean Contains(Int32)”,因此该方法无法转换为存储表达式。
究其原因,是Contains是IList类型的扩展方法而linq无法转换过来。所以上述办法就无法得到我们想要的结果(虽然编译不会有错)。
但可喜的是可以使用string类型的扩展方法Contains;当然这里需要在原表增加计算字段
[IDSearched] AS ((','+CONVERT([varchar](10),[RID],0))+',')
而获取数据的Linq查询语句就可以这样实现:
string ids = ",2,3,4,5,";
var list = context.TestTables.Where(a => ids.Contains(a.IDSearched)).ToList();
var list = context.TestTables.Where(a => ids.Contains(a.IDSearched)).ToList();
上面语句运行时,LINQ To Entities会将其翻译为如下SQL语句:
SELECT
[Extent1].[RID] AS [RID],
[Extent1].[NAME] AS [NAME],
[Extent1].[ROWDATE] AS [ROWDATE],
[Extent1].[DBSID] AS [DBSID],
[Extent1].[BIRTHDATE] AS [BIRTHDATE],
[Extent1].[NOTE] AS [NOTE]
FROM [dbo].[TestTable] AS [Extent1]
WHERE (CAST(CHARINDEX([Extent1].[NOTE], 'hhh,ggg') AS int)) > 0
[Extent1].[RID] AS [RID],
[Extent1].[NAME] AS [NAME],
[Extent1].[ROWDATE] AS [ROWDATE],
[Extent1].[DBSID] AS [DBSID],
[Extent1].[BIRTHDATE] AS [BIRTHDATE],
[Extent1].[NOTE] AS [NOTE]
FROM [dbo].[TestTable] AS [Extent1]
WHERE (CAST(CHARINDEX([Extent1].[NOTE], 'hhh,ggg') AS int)) > 0