LINQ To Entities如何实现查询 select * from tableA where id in (1,2,3,4) ?
2010-04-03 13:47
681 查看
熟悉LINQ的朋友也许会碰到标题的问题,且很自然地想起使用下面地语句实现:
然而,运行发现系统会抛出如下异常:
LINQ to Entities 不识别方法“Boolean Contains(Int32)”,因此该方法无法转换为存储表达式。
究其原因,是Contains是IList类型的扩展方法而linq无法转换过来。所以上述办法就无法得到我们想要的结果(虽然编译不会有错)。
但可喜的是可以使用string类型的扩展方法Contains;当然这里需要在原表增加计算字段
而获取数据的Linq查询语句就可以这样实现:
上面语句运行时,LINQ To Entities会将其翻译为如下SQL语句:
IList<int> ids = new List<int> { 2, 3, 4 }; 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();
上面语句运行时,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
相关文章推荐
- LINQ中in的实现方法-LINQ To Entities如何实现查询 select * from tableA where id in (1,2,3,4)
- 在游标中如何实现Select * from AAA where BB in XXX
- mysql select *... where id in (select 字符串 from ... )查询结果问题?
- 解决 Select * from TableName where ID in (@ids) 问题
- LINQ to Entities 实现sql 关键字"In"方式总结
- LINQ to Entities 实现sql 关键字"In"方式总结
- 有多少行? SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2
- UCenter info: MySQL Query Error SQL:SELECT value FROM [Table]vars WHERE name=\'noteexists2′ Error:SELECT command denied to use
- 3.You need to extract details of those products in the SALES table where the PROD_ID column contains
- Linq与where实现查询(Linq to Entity)【IEnumerable与IEnumerator与IList】|自己实现foreach的功能
- select id from table 如何找出不连续的id..
- Linq to Sql 如何实现 in 与 not in
- LINQ to Entities 实现sql 关键字"In"方式总结
- 醉了,mysql的删除居然变得这么麻烦 delete from table where id in()
- LINQ to Entities 实现sql 关键字"In"方式总结
- C#: from in select ; m(linq where)
- Mysql模糊查询 select count(*) from sys_invitation where from_id like '%1006%';
- 学习并使用了两种linq to entity 的实现sql关键字in的查询方法
- LINQ to Entities 实现sql 关键字"In"方式总结
- LINQ to Entities 实现sql 关键字"In"方式总结