今天做的一个项目中。有一个这样的字断IDS varchar(100)
当传过来一个List<string>("16","17")时。要在IDS中查找IDS中含有16或17的字断。
IDS中是存放着这样的数据的。 16,17
1,2
3,16
好了。。。 有两种方法。一种是使用labmber 还有一种是使用SQL
labmber :
Code
ParameterExpression parameter = Expression.Parameter(typeof(ProductInfo), "t");
Expression prop = Expression.Property(parameter, "CategoryID");
Expression exp = null;
foreach (string s in ProductCategoryIDs)
{
Expression current = Expression.Call(
prop, typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }), Expression.Constant(s + ","));
exp = (exp == null ? current : Expression.Or(exp, current));
current = Expression.Call(
prop, typeof(string).GetMethod("Contains"), Expression.Constant("," + s + ","));
exp = (exp == null ? current : Expression.Or(exp, current));
current = Expression.Call(
prop, typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) }), Expression.Constant("," + s));
exp = (exp == null ? current : Expression.Or(exp, current));
current = Expression.Equal(prop, Expression.Constant(s));
exp = (exp == null ? current : Expression.Or(exp, current));
}
Expression<Func<ProductInfo, bool>> lambda = Expression.Lambda<Func<ProductInfo, bool>>(exp, parameter);
var ProductList = DC.ProductsInfo.Where(lambda);
这样就可以了。 productList 是一个SQL语句。。但没执行。你想多条件之类的都可以直接WHERE就OK了。
第二种:使用存储过程。 先写个分隔方法
Code
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[Product_GetProductById]
@strWhere nvarchar(500),
@pagesize int=100,
@pageindex int=1
as
declare @SQL nvarchar(4000) -- 主语句
SET @sql='
begin
with temptbl as (SELECT *,
ROW_NUMBER() OVER (ORDER BY ProductCode asc )AS Row from g_Product where 1=1 '+@strWhere+' )
SELECT * FROM temptbl where Row between (@pageindex-1)*@pagesize+1 and (@pageindex-1)*@pagesize+@pagesize
end
'
EXEC sp_executesql @sql,N'@pageIndex int,@pageSize int'
,@pageIndex,@pageSize
再写个分页的。
Code
ALTER procedure [dbo].[Product_GetProductById]
@strWhere nvarchar(500),
@pagesize int=100,
@pageindex int=1
as
declare @SQL nvarchar(4000) -- 主语句
SET @sql='
begin
with temptbl as (SELECT *,
ROW_NUMBER() OVER (ORDER BY ProductCode asc )AS Row from g_Product where 1=1 '+@strWhere+' )
SELECT * FROM temptbl where Row between (@pageindex-1)*@pagesize+1 and (@pageindex-1)*@pagesize+@pagesize
end
'
EXEC sp_executesql @sql,N'@pageIndex int,@pageSize int'
,@pageIndex,@pageSize
这样就可以了。直接把存储过程拖到DBML上。 因为直接拖上面是会变成int型的。需要改一下DBML方法。
本来想发到首页。 但首页要求太高。 再说这也没什么高深的技术。
项目的一点总结。。 呵呵。。。 OK 88