asp.net实现的MVC跨数据库多表联合动态条件查询功能示例

本文实例讲述了asp.net实现的MVC跨数据库多表联合动态条件查询功能。分享给大家供大家参考,具体如下:

一、控制器中方法

[HttpGet]
public ActionResult Search()
{
  ViewBag.HeadTitle = "搜索";
  ViewBag.MetaKey = "\"123\"";
  ViewBag.MetaDes = "\"456\"";
  string whereText = "";
  if (Security.HtmlHelper.GetQueryString("first", true) != string.Empty)
  {
    whereText += " and a.ParentId='" + StringFilter("first", true)+"'";
  }
  if (Security.HtmlHelper.GetQueryString("second", true) != string.Empty)
    whereText += " and a.categoryId='" + StringFilter("second",true)+"'";
  string valueStr = "";
  if (Security.HtmlHelper.GetQueryString("theme", true) != string.Empty)
    valueStr += StringFilter("theme", true) + ",";
  if (Security.HtmlHelper.GetQueryString("size", true) != string.Empty)
    valueStr += StringFilter("size", true) + ",";
  if (Security.HtmlHelper.GetQueryString("font", true) != string.Empty)
    valueStr += StringFilter("font", true) + ",";
  if (Security.HtmlHelper.GetQueryString("shape", true) != string.Empty)
    valueStr += StringFilter("shape", true) + ",";
  if (Security.HtmlHelper.GetQueryString("technique", true) != string.Empty)
    valueStr += StringFilter("technique", true) + ",";
  if (Security.HtmlHelper.GetQueryString("category", true) != string.Empty)
    valueStr += StringFilter("category", true) + ",";
  if (Security.HtmlHelper.GetQueryString("place", true) != string.Empty)
    valueStr += StringFilter("place", true) + ",";
  if (Security.HtmlHelper.GetQueryString("price", true) != string.Empty)
    valueStr += StringFilter("price", true) + ",";
  if (valueStr != "")
  {
    valueStr=valueStr.Substring(0, valueStr.Length - 1);
    whereText += " and f.valueId in("+valueStr+")";
  }
  if (Security.HtmlHelper.GetQueryString("searchKeys", true) != string.Empty)
    whereText += " and a.SaleTitle like '%'" + StringFilter("searchKes", true) + "'%' or a.SaleDes like '%'" + StringFilter("searchKes", true) + "'%' or a.SaleAuthor like '%'" + StringFilter("searchKes", true) + "'%' or a.KeyWords like '%'" + StringFilter("searchKes", true) + "'%' or g.valueProperty like '%'" + StringFilter("searchKes", true) + "'%'";
  int pageSize = 50;
  int pageIndex = HttpContext.Request.QueryString["pageIndex"].Toint(1);
  List<string> searchInfo = Search(pageIndex, pageSize, whereText, 1);
  if (Security.HtmlHelper.GetQueryString("sort", true) != string.Empty)
  {
    string sort = StringFilter("sort", true);
    switch (sort)
    {
      case "1":  //综合即默认按照上架时间降序排列即按照id降序
        searchInfo = Search(pageIndex, pageSize, whereText, 1);
        break;
      case"2":  //销量
        searchInfo = Search(pageIndex, pageSize, whereText,0, "saleTotal");
        break;
      case "3":  //收藏
        searchInfo = Search(pageIndex, pageSize, whereText,0, "favoritesTotal");
        break;
      case "4":  //价格升序
        searchInfo = Search(pageIndex, pageSize, whereText,1);
        break;
      case "5":  //价格降序
        searchInfo = Search(pageIndex, pageSize, whereText,2);
        break;
    }
  }
  string jsonStr = searchInfo[0];
  ViewData["jsondata"] = jsonStr;
  int allCount = Utility.Toint(searchInfo[1], 0);
  ViewBag.AllCount = allCount;
  ViewBag.MaxPages = allCount % pageSize == 0 ? allCount / pageSize : (allCount / pageSize + 1).Toint(1);
  return View();
}
[NonAction]
public List<string> Search(int pageIndex, int pageSize, string whereText, int orderByPrice, string orderBy = "SaleId")
{
  BLL.Products searchInfoBLL = new BLL.Products();
  List<string> searchInfo = searchInfoBLL.GetSearchInfo(pageIndex, pageSize, whereText, orderByPrice,orderBy);
  return searchInfo;
}

注:Security.HtmlHelper.GetQueryString(),StringFilter()为自己封装的方法,用于过滤参数值

二、BLL层方法

using System;
using System.Web;
using System.Web.Caching;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Web.Script.Serialization;
using FotosayMall.Model;
using FotosayMall.Common;
using System.Text.RegularExpressions;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using FotosayMall.MVC.Models;
namespace FotosayMall.BLL
{
  public class Products
  {
    private readonly DAL.Products dal = new DAL.Products();
    /// <summary>
    /// 分页查询,检索页数据
    /// </summary>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="orderByPrice">价格排序:0默认,1升序,2降序</param>
    /// <returns></returns>
    public List<string> GetSearchInfo(int pageIndex, int pageSize, string whereText, int orderByPrice, string orderBy = "SaleId")
    {
      DataSet searchInfoTables = dal.GetSearchInfo(pageIndex, pageSize, whereText);
      //总记录数
      int allCount = Utility.Toint(searchInfoTables.Tables[1].Rows[0]["rowsTotal"], 0);
      var searchInfo = from list in searchInfoTables.Tables[0].AsEnumerable().OrderByDescending(x => x.Table.Columns[orderBy])
        select new SearchModel
        {
         Url = "/home/products?saleId=" + list.Field<int>("SaleId"),
         Author = list.Field<string>("SaleAuthor"),
         PhotoFileName = list.Field<string>("PhotoFileName"),
         PhotoFilePathFlag = list.Field<int>("PhotoFilePathFlag"),
         Province = list.Field<string>("Place").Split(' ').First(),
         SalePrice = list.Field<decimal>("SalePrice"),
         UsingPrice = list.Field<decimal>("usingPrice"),
         Title = list.Field<string>("SaleTitle").Length > 30 ? list.Field<string>("SaleTitle").Substring(0, 30) : list.Field<string>("SaleTitle"),
         Year = list.Field<DateTime>("BuildTime").ToString("yyyy") == "1900" ? "" : list.Field<DateTime>("BuildTime").ToString("yyyy年")
        };
      if (orderByPrice==2)
        searchInfo = searchInfo.OrderByDescending(x => x.Price);
      else if (orderByPrice == 1)
        searchInfo = searchInfo.OrderBy(x => x.Price);
      string jsonStr = JsonConvert.SerializeObject(searchInfo);
      List<string> dataList = new List<string>();
      dataList.Add(jsonStr);
      dataList.Add(allCount.ToString());
      return dataList;
    }
  }
}

注:注意观察由DataTable转换为可枚举的可用于Linq查询的方法方式。

DAL

/// <summary>
/// 获取检索页数据
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public DataSet GetSearchInfo(int pageIndex, int pageSize, string whereText)
{
  StringBuilder sqlText = new StringBuilder();
  sqlText.Append("select * from (");
  sqlText.Append("select a.SaleId,a.PhotoId,SaleTitle,SaleAuthor,a.Status,a.categoryId,c.UserID,c.UserName,b.PhotoFilePathFlag,b.PhotoFileName,coalesce(e.BuildTime,0) BuildTime,c.Place,coalesce(d.usingPrice,0) usingPrice,coalesce(e.SalePrice,0) SalePrice,h.saleTotal,h.favoritesTotal,row_number() over(order by a.saleId) rowsNum ");
  sqlText.Append("from fotosay..Photo_Sale a join fotosay..Photo_Basic b on a.PhotoId = b.PhotoID ");
  sqlText.Append("join fotosay..System_AccountsDescription c on b.UserID = c.UserID ");
  sqlText.Append("left join fotosay..Photo_Sale_Picture d on a.SaleId = d.SaleId ");
  sqlText.Append("left join fotosay..Photo_Sale_Tangible e on a.saleId = e.saleId ");
  sqlText.Append("join FotosayMall..Fotomall_Product_Relation f on f.saleId = a.SaleId ");
  sqlText.Append("join FotosayMall..Fotomall_Product_PropertyValue g on g.categoryId = a.categoryId and g.valueId = f.valueId and g.propertyId = f.propertyId ");
  sqlText.Append("join fotosay..Photo_Sale_Property h on a.saleId = h.saleId ");
  sqlText.Append("where a.Status=1 " + whereText + " ");
  sqlText.Append("group by a.SaleId,a.PhotoId,SaleTitle,SaleAuthor,a.Status,a.categoryId,c.UserID,c.UserName,b.PhotoFilePathFlag,b.PhotoFileName,e.BuildTime,c.Place,usingPrice,SalePrice,h.saleTotal,h.favoritesTotal ");
  sqlText.Append(") t where rowsNum between @PageSize*(@PageIndex-1)+1 and @PageSize*@PageIndex;");
  sqlText.Append("select count(distinct a.saleId) rowsTotal from fotosay..Photo_Sale a join (select b1.PhotoFilePathFlag,b1.PhotoFileName,b1.UserID,b1.PhotoID from fotosay..Photo_Basic b1 union select b2.PhotoFilePathFlag,b2.PhotoFileName,b2.UserID,b2.PhotoID from fotosay..Photo_Basic_History b2 ) b on a.PhotoId = b.PhotoID join fotosay..System_AccountsDescription c on b.UserID = c.UserID left join fotosay..Photo_Sale_Picture d on a.SaleId = d.SaleId left join fotosay..Photo_Sale_Tangible e on a.saleId = e.saleId join FotosayMall..Fotomall_Product_Relation f on f.saleId = a.SaleId join FotosayMall..Fotomall_Product_PropertyValue g on g.categoryId = a.categoryId and g.valueId = f.valueId and g.propertyId = f.propertyId join fotosay..Photo_Sale_Property h on a.saleId = h.saleId where a.Status=1 " + whereText + ";");
  DbParameter[] parameters = {
    Fotosay.CreateInDbParameter("@PageIndex", DbType.Int32,pageIndex),
    Fotosay.CreateInDbParameter("@PageSize", DbType.Int32,pageSize)
    };
  DataSet searchInfoList = Fotosay.ExecuteQuery(CommandType.Text, sqlText.ToString(), parameters);
  //记录条数不够一整页,则查历史库
  if (searchInfoList.Tables[0].Rows.Count < pageSize)
  {
    string sql = "select top(1) a.saleId from fotosay..Photo_Sale a join fotosay..Photo_Basic_History b on a.PhotoId = b.PhotoID join fotosay..System_AccountsDescription c on b.UserID = c.UserID left join fotosay..Photo_Sale_Picture d on a.SaleId = d.SaleId left join fotosay..Photo_Sale_Tangible e on a.saleId = e.saleId join FotosayMall..Fotomall_Product_Relation f on f.saleId = a.SaleId join FotosayMall..Fotomall_Product_PropertyValue g on g.categoryId = a.categoryId and g.valueId = f.valueId and g.propertyId = f.propertyId join fotosay..Photo_Sale_Property h on a.saleId = h.saleId where a.Status=1 " + whereText + ";";
    DataSet ds = Fotosay.ExecuteQuery(CommandType.Text, sql.ToString(), parameters);
    if (ds != null && ds.Tables[0].Rows.Count > 0)
    {
      StringBuilder sqlTextMore = new StringBuilder();
      sqlTextMore.Append("select * from (");
      sqlTextMore.Append("select a.SaleId,a.PhotoId,SaleTitle,SaleAuthor,a.Status,a.categoryId,c.UserID,c.UserName,b.PhotoFilePathFlag,b.PhotoFileName,coalesce(e.BuildTime,0) BuildTime,c.Place,coalesce(d.usingPrice,0) usingPrice,coalesce(e.SalePrice,0) SalePrice,h.saleTotal,h.favoritesTotal,row_number() over(order by a.saleId) rowsNum ");
      sqlTextMore.Append("from fotosay..Photo_Sale a ");
      sqlTextMore.Append("join (select b1.PhotoFilePathFlag,b1.PhotoFileName,b1.UserID,b1.PhotoID from fotosay..Photo_Basic b1 union select b2.PhotoFilePathFlag,b2.PhotoFileName,b2.UserID,b2.PhotoID from fotosay..Photo_Basic_History b2 ) b on a.PhotoId = b.PhotoID join fotosay..System_AccountsDescription c on b.UserID = c.UserID ");
      sqlTextMore.Append("left join fotosay..Photo_Sale_Picture d on a.SaleId = d.SaleId ");
      sqlTextMore.Append("left join fotosay..Photo_Sale_Tangible e on a.saleId = e.saleId ");
      sqlTextMore.Append("join FotosayMall..Fotomall_Product_Relation f on f.saleId = a.SaleId ");
      sqlTextMore.Append("join FotosayMall..Fotomall_Product_PropertyValue g on g.categoryId = a.categoryId and g.valueId = f.valueId and g.propertyId = f.propertyId ");
      sqlTextMore.Append("join fotosay..Photo_Sale_Property h on a.saleId = h.saleId ");
      sqlTextMore.Append("where a.Status=1 " + whereText + " ");
      sqlTextMore.Append("group by a.SaleId,a.PhotoId,SaleTitle,SaleAuthor,a.Status,a.categoryId,c.UserID,c.UserName,b.PhotoFilePathFlag,b.PhotoFileName,e.BuildTime,c.Place,usingPrice,SalePrice,h.saleTotal,h.favoritesTotal");
      sqlTextMore.Append(") t where rowsNum between @PageSize*(@PageIndex-1)+1 and @PageSize*@PageIndex;");
      sqlTextMore.Append("select count(distinct a.saleId) rowsTotal from fotosay..Photo_Sale a join (select b1.PhotoFilePathFlag,b1.PhotoFileName,b1.UserID,b1.PhotoID from fotosay..Photo_Basic b1 union select b2.PhotoFilePathFlag,b2.PhotoFileName,b2.UserID,b2.PhotoID from fotosay..Photo_Basic_History b2 ) b on a.PhotoId = b.PhotoID join fotosay..System_AccountsDescription c on b.UserID = c.UserID left join fotosay..Photo_Sale_Picture d on a.SaleId = d.SaleId left join fotosay..Photo_Sale_Tangible e on a.saleId = e.saleId join FotosayMall..Fotomall_Product_Relation f on f.saleId = a.SaleId join FotosayMall..Fotomall_Product_PropertyValue g on g.categoryId = a.categoryId and g.valueId = f.valueId and g.propertyId = f.propertyId join fotosay..Photo_Sale_Property h on a.saleId = h.saleId where a.Status=1 " + whereText + ";");
      searchInfoList = Fotosay.ExecuteQuery(CommandType.Text, sqlTextMore.ToString(), parameters);
    }
  }
  return searchInfoList;
}

注:注意其中使用的跨数据库查询的方式和union的一种使用方式

Model

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace FotosayMall.MVC.Models
{
  public class SearchModel
  {
    /// <summary>
    /// 原始图片文件夹(用于url地址)
    /// </summary>
    private const string OriginImagesUrlFolder = "userimages/photos_origin";
    /// <summary>
    /// 购买页链接
    /// </summary>
    public string Url { get; set; }
    /// <summary>
    /// 所属域名(1为fotosay,2为img,3为img1)
    /// </summary>
    public int PhotoFilePathFlag { get; set; }
    /// <summary>
    /// 图片名称
    /// </summary>
    public string PhotoFileName { get; set; }
    /// <summary>
    /// 商品名称
    /// </summary>
    public string Title { get; set; }
    /// <summary>
    /// 作者所在省份
    /// </summary>
    public string Province { get; set; }
    /// <summary>
    /// 作者
    /// </summary>
    public string Author { get; set; }
    /// <summary>
    /// 创作年份
    /// </summary>
    public string Year { get; set; }
    /// <summary>
    /// 图片:单次价格
    /// </summary>
    public decimal UsingPrice { get; set; }
    /// <summary>
    /// 实物:定价
    /// </summary>
    public decimal SalePrice { get; set; }
    /// <summary>
    /// 售价
    /// </summary>
    public string Price
    {
      get
      {
        if (this.UsingPrice > 0)
          return this.UsingPrice.ToString();
        else if (this.SalePrice > 0)
          return this.SalePrice.ToString();
        else
          return "议价";
      }
    }
    /// <summary>
    ///
    /// </summary>
    private string MasterSite
    {
      get { return ConfigurationManager.AppSettings["masterSite"].ToString(); }
    }
    /// <summary>
    /// 图片完整路径
    /// </summary>
    public string Img
    {
      get
      {
        return MasterSite + "/" + OriginImagesUrlFolder + this.PhotoFileName + "b.jpg";
      }
    }
  }
}

更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net优化技巧总结》、《asp.net字符串操作技巧汇总》、《asp.net操作XML技巧总结》、《asp.net文件操作技巧汇总》、《asp.net ajax技巧总结专题》及《asp.net缓存操作技巧总结》。

希望本文所述对大家asp.net程序设计有所帮助。

(0)

相关推荐

  • sqlserver 多表查询不同数据库服务器上的表

    第一种方法: 复制代码 代码如下: /* 创建链接服务器 */ exec sp_addlinkedserver 'srv_lnk','','sqloledb','条码数据库IP地址' exec sp_addlinkedsrvlogin 'srv_lnk','false',null,'用户名','密码' go /* 查询示例 */ SELECT A.ListCode FROM srv_lnk.条码数据库名.dbo.ME_ListCode A, IM_BarLend B WHERE A.ListCo

  • 详解数据库多表连接查询的实现方法

    详解数据库多表连接查询的实现方法 通过连接运算符可以实现多个表查询.连接是关系数据库模型的主要特点,也是它区别于其它类型数据库管理系统的一个标志. 在关系数据库管理系统中,表建立时各数据之间的关系不必确定,常把一个实体的所有信息存放在一个表中.当检索数据时,通过连接操作查询出存放在多个表中的不同实体的信息.连接操作给用户带来很大的灵活性,他们可以在任何时候增加新的数据类型.为不同实体创建新的表,尔后通过连接进行查询. 连接可以在SELECT 语句的FROM子句或WHERE子句中建立,似是而非在F

  • asp.net实现的MVC跨数据库多表联合动态条件查询功能示例

    本文实例讲述了asp.net实现的MVC跨数据库多表联合动态条件查询功能.分享给大家供大家参考,具体如下: 一.控制器中方法 [HttpGet] public ActionResult Search() { ViewBag.HeadTitle = "搜索"; ViewBag.MetaKey = "\"123\""; ViewBag.MetaDes = "\"456\""; string whereText

  • mysql跨数据库复制表(在同一IP地址中)示例

    数据库表间数据复制分类 在利用数据库开发时,常常会将一些表之间的数据互相导入.当然可以编写程序实现,但是,程序常常需要开发环境,不方便.最方便是利用sql语言直接导入.既方便而修改也简单.以下就是导入的方法. 1. 表结构相同的表,且在同一数据库(如,table1,table2) Sql : 复制代码 代码如下: insert into table1 select   *    from table2 (完全复制)insert into table1 select   distinct   * 

  • 利用PHP访问数据库_实现分页功能与多条件查询功能的示例

    1.实现分页功能 <body> <table width="100%" border="1"> <thead> <tr> <th>代号</th> <th>名称</th> <th>价格</th> </tr> </thead> <tbody> <?php require_once "./DBDA.cl

  • Spring MVC结合Spring Data JPA实现按条件查询和分页

    本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下 推荐视频:尚硅谷Spring Data JPA视频教程,一学就会,百度一下就有. 后台代码:在DAO层继承Spring Data JPA的PagingAndSortingRepository接口实现的 (实现方法主要在SbglServiceImpl.java类中) 前台表现:用kkpaper表现出来 实现效果: 1.实体类 package com.jinhetech.yogurt.sbgl.entity; im

  • Java操作Mongodb数据库实现数据的增删查改功能示例

    本文实例讲述了Java操作Mongodb数据库实现数据的增删查改功能.分享给大家供大家参考,具体如下: 首先,我们在windows下安装mongodb数据库,安装教程可查看前面一篇文章:http://www.jb51.net/article/85605.htm 代码如下: package io.mogo; import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.mongodb.BasicDBObj

  • ASP多条件查询功能实现代码(多关键词查询)

    经过多次研究写出了如下代码,有需要的可以参考下 复制代码 代码如下: kd=server.HTMLEncode(request("keyword"))if kd<>"" then    kd=trim(kd)'kd=replace(kd," ","")  kd=replace(kd,"'","")  kd=replace(kd,"%","&quo

  • 跨数据库实现数据交流

    通常情况下,我们的CRUD操作都在单一数据库中进行.但是,也可能会遇到需要进行跨数据交流的情况.对此,我以跨数据库进行表的访问为例,稍微总结了下. 一.同SQL SERVER 这个最简单.直接在表名前加上"[数据库名]."就可以了. 例: SELECT * FROM [DestinationDBName].dbo.DestinationTableName 二.跨SQL SERVER 主要介绍两种方法: (一)通过链接服务器 1.先执行系统存储过程 sp_addlinkedserver

  • Java的MyBatis框架中对数据库进行动态SQL查询的教程

    其实MyBatis具有的一个强大的特性之一通常是它的动态 SQL 能力. 如果你有使用 JDBC 或其他 相似框架的经验,你就明白要动态的串联 SQL 字符串在一起是十分纠结的,确保不能忘了空格或在列表的最后省略逗号.Mybatis中的动态 SQL 可以彻底处理这种痛苦.对于动态SQL,最通俗简单的方法就是我们自己在硬编码的时候赋予各种动态行为的判断,而在Mybatis中,用一种强大的动态 SQL 语 言来改进这种情形,这种语言可以被用在任意映射的 SQL 语句中.动态 SQL 元素和使用 JS

  • ASP.NET Core2读写InfluxDB时序数据库的方法教程

    前言 在我们很多应用中会遇到有一种基于一系列时间的数据需要处理,通过时间的顺序可以将这些数据点连成线,再通过数据统计后可以做成多纬度的报表,也可通过机器学习来实现数据的预测告警.而时序数据库就是用于存放管理这种有着时间顺序数据的,时序数据库一般都支持时序数据的快速写入.持久化.多纬度的聚合查询等基本功能. InfluxDB简介 InfluxDB是一个基于时间序列数据而开发的高性能数据存储平台,它可以对时序数据进行高吞吐量的摄取.压缩和实时查询.InfluxDB是用Go语言编写的,它会编译成一个没

  • ASP.NET(C#)中操作SQLite数据库实例

    要想在ASP.NET项目中使用SQLite数据库,先需下载一个ADO.NET 2.0 SQLite Data Provider,下载地址为:http://sourceforge.net/project/showfiles.php?group_id=132486&package_id=145568,下载后安装完毕后,该安装程序自动在在系统注册(即可在"添加引用"中看到所安装的Provider).     然后,在项目中添加上图所选项即可. aspx页面仅包含一按钮btnTest,

随机推荐