// 程序目的为了实现多关键字查询
SourceDataContext s = new SourceDataContext();
IQueryable<vw_source_list> result = s.vw_source_list;//vw_source_list 为一个表
//方式一 关键字在数组keys数组里面,采用遍历的方法,不成功,只能把最后的b传过去
string[] keys = { "a", "b" };
foreach (string key in keys)
{
result = result.Where(t => t.source_subject.Contains(key));
}
//方式二 关键字在数组keys2数组里面,采用直接传值的方法,成功
string[] keys2 = { "c", "d" };
result = result.Where(t => t.source_subject.Contains(keys2[0]));
result = result.Where(t => t.source_subject.Contains(keys2[1]));
//输出
var sql = s.GetCommand(result.Select(t => t.id)).CommandText;
//sql内容为:
//SELECT [t0].[id]
//FROM [dbo].[WCMS_vw_source_list] AS [t0]
//WHERE ([t0].[source_subject] LIKE @p0)
// AND ([t0].[source_subject] LIKE @p1)
// AND ([t0].[source_subject] LIKE @p2)
// AND ([t0].[source_subject] LIKE @p3)
var exp = result.Select(t => t.id).Expression;
//exp内容为:
//{Table(vw_source_list)
//.Where(t => t.source_subject.Contains(value(WMVC.Controllers.SourceBrowserController+<>c__DisplayClassb).key))
//.Where(t => t.source_subject.Contains(value(WMVC.Controllers.SourceBrowserController+<>c__DisplayClassb).key))
//.Where(t => t.source_subject.Contains(value(WMVC.Controllers.SourceBrowserController+<>c__DisplayClass7).keys2[0]))
//.Where(t => t.source_subject.Contains(value(WMVC.Controllers.SourceBrowserController+<>c__DisplayClass7).keys2[1]))
//.Select(t => t.id)}
//触发Linq查询数据库
foreach (var item in result)
{
Console.WriteLine(item.id);
}
//MSSQL里面监控结果如下:
//sql语句
//SELECT [t0].[id],[t0].[source_subject]
//FROM [dbo].[WCMS_vw_source_list] AS [t0]
//WHERE ([t0].[source_subject] LIKE @p0)
// AND ([t0].[source_subject] LIKE @p1)
// AND ([t0].[source_subject] LIKE @p2)
// AND ([t0].[source_subject] LIKE @p3)
//参数
//@p0=N'%d%',
//@p1=N'%c%',
//@p2=N'%b%',
//@p3=N'%b%' !!!! "a" 没传过来!!!!
//请问:如何用方式一把关键字传过来,也就是关键字数未定的情况下,怎么写where Contains ?
result= result.Where(c=>keys.All(k=>c.source_subject.Contains(k) ))