今天做的一個項目中。有一個這樣的字斷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