最近在弄一個東東,相似那種CMS的後臺管理系統,方便做爲其它項目的初始化框架用的。javascript
如今遇到個問題,如標題所示:Dapper通用的多表聯合分頁查詢怎麼破?css
單表的話很簡單就能夠實現,多表不通用的話也能夠很方便的實現,那麼若是多表通用的話,怎麼辦呢?html
難道只能經過拼接sql或者使用存儲過程嗎?我先來展現下個人實現方式,但願你有更好的方式,而後同我分享一下,以便解決個人困擾。java
由於原本就是作的傳統的CMS相似的項目,因此技術選型也是比較傳統,拋棄了mvvm的js框架、webapi接口、以及nosql緩存。jquery
技術選型:MVC五、Mysql、Dapper、Autofac、Layui、阿里巴巴矢量庫、T4(後面補上)。程序員
我選擇的都是輕量級比較乾淨的東東來組合的框架。web
我選擇由外入內的方式來闡述我如今遇到的問題。以用戶管理界面爲例,我講只列出涉及到用戶分頁查詢的代碼,將會省略其它代碼.....ajax
大體上的效果以下圖所示:sql
經典的多層架構數據庫
Global.asax.cs代碼,Dapper自動注入。
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //建立autofac管理註冊類的容器實例 var builder = new ContainerBuilder(); SetupResolveRules(builder); //使用Autofac提供的RegisterControllers擴展方法來對程序集中全部的Controller一次性的完成註冊 支持屬性注入 builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); // 把容器裝入到微軟默認的依賴注入容器中 var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } private static void SetupResolveRules(ContainerBuilder builder) { //WebAPI只用引用services和repository的接口,不用引用實現的dll。 //如需加載實現的程序集,將dll拷貝到bin目錄下便可,不用引用dll var iServices = Assembly.Load("RightControl.IService"); var services = Assembly.Load("RightControl.Service"); var iRepository = Assembly.Load("RightControl.IRepository"); var repository = Assembly.Load("RightControl.Repository"); //根據名稱約定(服務層的接口和實現均以Services結尾),實現服務接口和服務實現的依賴 builder.RegisterAssemblyTypes(iServices, services) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces().PropertiesAutowired(); //根據名稱約定(數據訪問層的接口和實現均以Repository結尾),實現數據訪問接口和數據訪問實現的依賴 builder.RegisterAssemblyTypes(iRepository, repository) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces().PropertiesAutowired(); } }
BaseController:
public class BaseController : Controller {// GET: Base public virtual ActionResult Index() { return View(); }
UserController:
public class UserController : BaseController { private IUserService service; public UserController(IUserService _service) { service = _service; } /// <summary> /// 加載數據列表 /// </summary> /// <param name="pageInfo">頁面實體信息</param> /// <param name="filter">查詢條件</param> /// <returns></returns> [HttpGet] public JsonResult List(PageInfo pageInfo, UserModel filter) { var result = service.GetListByFilter(filter, pageInfo); return Json(result, JsonRequestBehavior.AllowGet); }
PageInfo:
public class PageInfo { public int page { get; set; } public int limit { get; set; } /// <summary> /// 排序字段 CreateOn /// </summary> public string field { get; set; } /// <summary> /// 排序方式 asc desc /// </summary> public string order { get; set; } /// <summary> /// 返回字段逗號分隔 /// </summary> public string returnFields { get; set; } public string prefix { get; set; } }
UserModel:
using DapperExtensions; using System; using System.ComponentModel.DataAnnotations; namespace RightControl.Model { [Table("t_User")] public class UserModel:Entity { /// <summary> /// 用戶名 /// </summary> [Display(Name = "用戶名")] public string UserName { get; set; } /// <summary> /// 真實名稱 /// </summary> [Display(Name = "真實名稱")] public string RealName { get; set; } /// <summary> /// 密碼 /// </summary> public string PassWord { get; set; } /// <summary> /// 建立者 /// </summary> public int CreateBy { get; set; } /// <summary> /// 角色ID /// </summary> public int RoleId { get; set; } /// <summary> /// 更新時間 /// </summary> [Display(Name = "更新時間")] public DateTime UpdateOn { get; set; } [Computed] public string RoleName { get; set; } } }
Entity:
public class Entity { [DapperExtensions.Key(true)] public virtual int Id { get; set; } /// <summary> /// 建立時間 /// </summary> [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}")] [Display(Name = "建立時間")] public DateTime CreateOn { get; set; } /// <summary> /// 菜單狀態(1:啓用,0:禁用) /// </summary> public bool Status { get; set; } #region 查詢條件 [Computed] public string StartEndDate { get; set; } #endregion }
IBaseService:
public interface IBaseService<T> where T : class, new() { dynamic GetListByFilter(T filter, PageInfo pageInfo); }
IUserService:
public interface IUserService : IBaseService<UserModel> { ... }
BaseService:
public abstract class BaseService<T> where T : class, new() { public IBaseRepository<T> baseRepository{get; set;} public dynamic GetPageUnite(IBaseRepository<T> repository, PageInfo pageInfo, string where, object filter) { string _orderBy = string.Empty; if (!string.IsNullOrEmpty(pageInfo.field)) { _orderBy = string.Format(" ORDER BY {0} {1}", pageInfo.prefix+pageInfo.field, pageInfo.order); } else { _orderBy = string.Format(" ORDER BY {0}CreateOn desc",pageInfo.prefix); } long total = 0; var list = repository.GetByPageUnite(new SearchFilter { pageIndex = pageInfo.page, pageSize = pageInfo.limit, returnFields = pageInfo.returnFields, param = filter, where = where, orderBy = _orderBy }, out total); return Pager.Paging(list, total); } protected string CreateWhereStr(Entity filter, string _where) { if (!string.IsNullOrEmpty(filter.StartEndDate) && filter.StartEndDate != " ~ ") { var dts = filter.StartEndDate.Trim().Split('~'); var start = dts[0].Trim(); var end = dts[1].Trim(); if (!string.IsNullOrEmpty(start)) { _where += string.Format(" and CreateOn>='{0}'", start + " 00:00"); } if (!string.IsNullOrEmpty(end)) { _where += string.Format(" and CreateOn<='{0}'", end + " 59:59"); } } return _where; } }
UserService:
public class UserService: BaseService<UserModel>, IUserService { public IUserRepository repository { get; set; }//屬性注入 public dynamic GetListByFilter(UserModel filter, PageInfo pageInfo) { pageInfo.prefix = "u."; string _where = " t_User u INNER JOIN t_role r on u.RoleId=r.Id"; if (!string.IsNullOrEmpty(filter.UserName)) { _where += string.Format(" and {0}UserName=@UserName",pageInfo.prefix); } if (!string.IsNullOrEmpty(pageInfo.order)) { pageInfo.order = pageInfo.prefix + pageInfo.order; } pageInfo.returnFields = string.Format("{0}Id,{0}UserName,{0}RealName,{0}CreateOn,{0}`PassWord`,{0}`Status`,{0}RoleId,r.RoleName",pageInfo.prefix); return GetPageUnite(baseRepository, pageInfo, _where, filter); }
IBaseRepository:
public interface IBaseRepository<T> where T : class, new() { IEnumerable<T> GetByPageUnite(SearchFilter filter, out long total); }
IUserRepository:
public interface IUserRepository : IBaseRepository<UserModel> { }
BaseRepository:
public class BaseRepository<T>: IBaseRepository<T> where T :class, new() { public IEnumerable<T> GetByPageUnite(SearchFilter filter, out long total) { using (var conn = MySqlHelper.GetConnection()) { return conn.GetByPageUnite<T>(filter.pageIndex, filter.pageSize, out total, filter.returnFields, filter.where, filter.param, filter.orderBy, filter.transaction, filter.commandTimeout); } } }
UserRepository:
public class UserRepository : BaseRepository<UserModel>, IUserRepository { }
最後的分頁代碼:
/// <summary> /// 獲取分頁數據 /// </summary> public static IEnumerable<T> GetByPageUnite<T>(this IDbConnection conn, int pageIndex, int pageSize, out long total, string returnFields = null, string where = null, object param = null,
string orderBy = null, IDbTransaction transaction = null, int? commandTimeout = null) { int skip = 0; if (pageIndex > 0) { skip = (pageIndex - 1) * pageSize; } StringBuilder sb = new StringBuilder(); sb.AppendFormat("SELECT COUNT(1) FROM {0};", where); sb.AppendFormat("SELECT {0} FROM {1} {2} LIMIT {3},{4}", returnFields, where, orderBy, skip, pageSize); using (var reader = conn.QueryMultiple(sb.ToString(), param, transaction, commandTimeout)) { total = reader.ReadFirst<long>(); return reader.Read<T>(); } }
Index視圖:
@{ Layout = "~/Views/Shared/_LayoutList.cshtml"; } <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Table</title> </head> <body> <div class="admin-main"> <blockquote class="layui-elem-quote p10"> <form id="formSearch" class="layui-form" action=""> <div class="layui-form-item" style="margin-bottom:0px;"> <label class="layui-form-label">用戶名稱:</label> <div class="layui-input-inline"> <input name="UserName" id="UserName" lay-verify="" autocomplete="off" class="layui-input"> </div> <label class="layui-form-label">角色名稱:</label> <div class="layui-input-inline"> @Html.DropDownList("RoleId", null, "-請選擇角色-", new Dictionary<string, object> { { "lay-verify", "required" } }) </div> <label class="layui-form-label">狀態:</label> <div class="layui-input-inline"> @Html.StatusSelectHtml() </div> @Html.SearchBtnHtml() @Html.ResetBtnHtml() <div style="float:right;"> @Html.TopToolBarHtml(ViewData["ActionFormRightTop"]) </div> </div> </form> </blockquote> <div class="layui-field-box"> <table id="defaultTable" lay-filter="defaultruv"></table> <!-- 這裏的 checked 的狀態只是演示 --> @*<input type="checkbox" name="Status" value="{{d.Id}}" lay-skin="switch" lay-text="開啓|禁用" lay-filter="statusSwitch" {{ d.Status == 1 ? 'checked' : '' }}>*@ <script type="text/html" id="bar"> @Html.ToolBarHtml(ViewData["ActionList"]) </script> </div> </div> <script> layui.config({ base: '/plugins/app/' }); layui.use(['table', 'common', 'form'], function () { var table = layui.table, form = layui.form, common = layui.common; //表格 table.render({ id: 'defaultReload' , elem: '#defaultTable' , height: 'full-112' //高度最大化減去差值 , url: '/Permissions/User/List' //數據接口 , page: true //開啓分頁 , cols: [[ //表頭 { checkbox: true, fixed: true }, { field: 'Id', title: 'Id', width: 80, fixed: 'left' } , { field: 'UserName', title: '用戶名稱', sort: true } , { field: 'RealName', title: '真實姓名' } , { field: 'RoleName', title: '角色名稱' } , { field: 'Status', title: '狀態', templet: '<div>{{showStatus(d.Status)}}</div>', unresize: true, width: 100, align: 'center' } , { field: 'CreateOn', title: '建立時間', width: 160, sort: true, templet: '<div>{{showDate(d.CreateOn)}}</div>' } , { field: '', title: '操做', toolbar: "#bar" } ]] }); var $ = layui.$, active = { reload: function () { var jsonWhere = urlToJson($("#formSearch").serialize()); //執行重載 table.reload('defaultReload', { page: { curr: 1 //從新從第 1 頁開始 } , where: jsonWhere }); } }; //服務器排序 table.on('sort(defaultruv)', function (obj) { //儘管咱們的 table 自帶排序功能,但並無請求服務端。 //有些時候,你可能須要根據當前排序的字段,從新向服務端發送請求,如: table.reload('defaultReload', { initSort: obj //記錄初始排序,若是不設的話,將沒法標記表頭的排序狀態。 layui 2.1.1 新增參數 , where: { //請求參數 field: obj.field //排序字段 , order: obj.type //排序方式 } }); }); $('#btnSearch').on('click', function () { var type = $(this).data('type'); active[type] ? active[type].call(this) : ''; }); //add $('#btnAdd').on('click', function () { common.openTop({ title: '用戶添加', w: '600px', h: '360px', content: '/Permissions/User/Add/' }); }); //監聽工具條 table.on('tool(defaultruv)', function (obj) { var data = obj.data; if (obj.event === 'detail') { common.openTop({ detail: true, title: '角色詳情', w: '600px', h: '360px', content: '/Permissions/User/Detail/' + data.Id, clickOK: function (index) { common.close(index); } }); } else if (obj.event === 'del') { layer.confirm('肯定要刪除嗎?', function (index) { $.ajax({ url: "/Permissions/User/Delete", type: "POST", data: { "Id": data.Id }, dataType: "json", success: function (data) { if (data.state == "success") { obj.del();//刪除這一行 common.msgSuccess("刪除成功"); } else { common.msgError("刪除失敗"); } layer.close(index);//關閉彈框 } }); }); } else if (obj.event === 'edit') { common.openTop({ title: '用戶編輯', w: '600px', h: '360px', content: '/Permissions/User/Edit/' + data.Id }); } else if (obj.event === 'reset') { layer.confirm('肯定要初始化密碼嗎?', function (index) { $.ajax({ url: "/Permissions/User/InitPwd", type: "POST", data: { "Id": data.Id }, dataType: "json", success: function (data) { if (data.state == "success") { layer.close(index);//關閉彈框 common.msgSuccess("密碼初始化成功"); } else { common.msgError("密碼初始化失敗"); } layer.close(index);//關閉彈框 } }); }); } }); }); </script> </body> </html>
_LayoutBase模板頁:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> <link rel="stylesheet" href="~/plugins/layui/css/layui.css" media="all" /> <link href="~/Content/global.css" rel="stylesheet" /> <link href="~/Content/table.css" rel="stylesheet" /> <script src="~/plugins/layui/layui.js"></script> <script src="~/plugins/app/global.js"></script> </head> <body> <div id="ajax-loader" style="cursor: progress; position: fixed; top: -50%; left: -50%; width: 200%; height: 200%; background: #fff; z-index: 10000; overflow: hidden;"> <img src="~/Content/images/ajax-loader.gif" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;" /> </div> @RenderBody() <script type="text/javascript"> layui.config({ base: '/plugins/app/', version: '1522709297490' //爲了更新 js 緩存,可忽略 }); layui.use(['common'], function () { layer.config({ skin: 'layui-layer-molv' }) var $ = layui.jquery; $(function () { $('#ajax-loader').fadeOut(); }) }) </script> </body> </html>
代碼結構基本上就這樣了。
做爲一名有追求的程序員,當看到代碼連本身都受不了,我就開始抓狂,每次寫代碼的時候,腦殼裏都是那幾句話「不要重複你的代碼、依賴於抽象....」
項目詳細介紹和代碼獲取請移步:.net項目驅動學習