在开发中我们常需要使用动态的条件来组合查询,scotte博客里提到了MS提供的一个动态查询类库Basic Dynamic LINQ C# Sample,这个可以给我们提供不少方便,但是给的示例实在太简单,实际当中我们很多不能像他这样用。
首先引入DynamicLibrary.cs,下面是我使用过程中的一些运行正确的用法(里面使用返回DataSet是因为对旧程序升级),我觉得写法很怪异,但是的确这样是正确的。
调用
最终生成的SQL语句
SELECT
COUNT
(
*
)
AS
[
value
]
FROM [ dbo ] . [ News ] AS [ t0 ]
WHERE ( [ t0 ] . [ NewsIsDeleted ] IS NULL ) AND ( [ t0 ] . [ NewsIsDisplay ] = 1 )
AND ( [ t0 ] . [ Newslanguages ] = @p0 ) AND ( [ t0 ] . [ NewsIsHome ] = 1 ) AND ( [ t0 ] . [ NewsIsTop ] = 1 )
-- @p0: Input NVarChar (Size = 8; Prec = 0; Scale = 0) [engbtest]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8
FROM [ dbo ] . [ News ] AS [ t0 ]
WHERE ( [ t0 ] . [ NewsIsDeleted ] IS NULL ) AND ( [ t0 ] . [ NewsIsDisplay ] = 1 )
AND ( [ t0 ] . [ Newslanguages ] = @p0 ) AND ( [ t0 ] . [ NewsIsHome ] = 1 ) AND ( [ t0 ] . [ NewsIsTop ] = 1 )
-- @p0: Input NVarChar (Size = 8; Prec = 0; Scale = 0) [engbtest]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8
另外分享一个query to datareader的方法,有了datareader可以生成datatable,dataset等:
注:不知各位有没有更好的办法?
本文转自敏捷的水博客园博客,原文链接http://www.cnblogs.com/cnblogsfans/archive/2008/04/01/1132918.html如需转载请自行联系原作者
王德水