在界面层中的代码:

 

List<SearchModel> ss = new List<SearchModel>();
if (!string.IsNullOrEmpty(Request.Form["txtName"]))//如果用户在名字框中输入了文字
{
SearchModel model = new SearchModel();
model.Name = "BookName";//要操作的字段为书名
model.Value = Request.Form["txtName"];//对应的值为用户输入的文字
model.Action = Action.Like;//操作为like
ss.Add(model);
}//以下类似
if (!string.IsNullOrEmpty(Request.Form["txtAuthor"]))
{
SearchModel model = new SearchModel();
model.Name = "Author";
model.Value = Request.Form["txtAuthor"];
model.Action = Action.Like;
ss.Add(model);
}
if (!string.IsNullOrEmpty(Request.Form["categoryId"]))
{
SearchModel model = new SearchModel();
model.Name = "CategoryId";
model.Value = Request.Form["categoryId"];
model.Action = Action.Equart;
ss.Add(model);
}
if (!string.IsNullOrEmpty(Request.Form["publisherId"]))
{
SearchModel model = new SearchModel();
model.Name = "PublisherId";
model.Value = Request.Form["publisherId"];
model.Action = Action.Equart;
ss.Add(model);
}
if (!string.IsNullOrEmpty(Request.Form["txtISBN"]))
{
SearchModel model = new SearchModel();
model.Name = "ISBN";
model.Value = Request.Form["txtISBN"];
model.Action = Action.Like;
ss.Add(model);
}
if (!string.IsNullOrEmpty(Request.Form["isDiscount"]))
{
SearchModel model = new SearchModel();
model.Name = "Discount";
model.Value = "1";
model.Action = Action.Equart;
ss.Add(model);
}
List<T_Books> books = searchBll.Searc(ss);//这里调用Bll进行操作

  Bll先不说,主要是Dal层的sql拼接

 

public List<T_Books> Search(List<SearchModel> ss)//接收传进来的条件模型类集合,并对其进行遍历
{
string sql = "select * from T_Books where IsDelete=0 and ";//开始拼接sql语句
for (int i = 0; i < ss.Count; i++)
{
if (ss[i].Action == Action.Like)
{
sql += ss[i].Name + " like '%" + ss[i].Value + "%'";
}
if (ss[i].Action == Action.Equart)
{
sql += ss[i].Name + " = " + ss[i].Value;
}
if (ss[i].Action == Action.Greatthan)
{
sql += ss[i].Name + " > " + ss[i].Value;
}
if (ss[i].Action == Action.Lessthan)
{
sql += ss[i].Name + " < " + ss[i].Value;
}
if (i != ss.Count - 1)
{
sql += " and ";
}
}
List<T_Books> list = new List<T_Books>();
DataTable table = SqlHelper.ExecuteDataTable(sql, CommandType.Text);//将拼接好的sql语句传入,开始查询数据库
foreach (DataRow row in table.Rows)
{
T_Books book = GetModelByDataRow.GetBooks(row);
list.Add(book);
}
return list;//返回符合条件的图书集合,完成
}
  假设用户输入下图的条件:
  后贴上测试拼接的sql语句,如下
  select * from T_Books where IsDelete=0 and BookName like '%C++%' and Author like '%JChubby%' and CategoryId = 15 and PublisherId = 16 and ISBN like '%1111%' and Discount = 1
  大功告成~!