首页 > 代码库 > LINQ中in的实现方法-LINQ To Entities如何实现查询 select * from tableA where id in (1,2,3,4)
LINQ中in的实现方法-LINQ To Entities如何实现查询 select * from tableA where id in (1,2,3,4)
如果用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
LINQ中in的实现方法-LINQ To Entities如何实现查询 select * from tableA where id in (1,2,3,4)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。