asp.net mvc 实战化项目之三板斧
接上文希望从一张表(tb_role_info 用户角色表)的CRUD展开asp.net mvc的项目实战化魅力。
开发技术选型:asp.net mvc+bootstrap+sqlserver。
项目目录结构:
(1)业务表 tb_role_info
-- ---------------------------- -- Table structure for `tb_role_info` 用户角色表 -- ---------------------------- DROP TABLE IF EXISTS `tb_role_info`; CREATE TABLE `tb_role_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `role_name` varchar(32) NOT NULL DEFAULT '' COMMENT '角色名称', `role_mark` varchar(255) DEFAULT '' COMMENT '角色备注', `creater_id` int(11) NOT NULL DEFAULT '0' COMMENT '记录创建者id', `created_at` timestamp NULL DEFAULT NULL COMMENT '创建日期', `updated_at` timestamp NULL DEFAULT NULL COMMENT '更新日期', `time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录更新时间戳', PRIMARY KEY (`id`), KEY `tb_role_info_index` (`id`,`role_name`,`creater_id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='角色信息表';
(2)业务界面 role.cshtml
@model Aptamil.Areas.Admin.ViewModels.RoleViewModel @{ Layout = null; } <!DOCTYPE html> <html> <head> @{Html.RenderPartial("Header");} <link rel="stylesheet" type="text/css" href="@Url.Content("~/Contents/backend/plugs/bootstrap-table/src/bootstrap-table.css")?v=@Model.Version" /> </head> <body> @{Html.RenderPartial("Navbar");} <div id="page-container"> <!-- BEGIN SIDEBAR --> @{Html.RenderPartial("Menu");} <!-- END SIDEBAR --> <!-- BEGIN RIGHTBAR --> <!-- END RIGHTBAR --> <div id="page-content"> <div id="wrap"> <div id="page-heading"> <ol class="breadcrumb"> <li><a href="#" title="icons">系统管理</a></li> <li class="active">角色信息</li> </ol> </div> <!-- container 内容显示区域begin--> <div class="container"> <div class='data-loading'></div> <div class="row"> <div class="col-xs-12"> <div id="search_panel" class="search-panel-body"> <form id="search_form" class="form-horizontal"> <div class="row"> <div class="col-md-10"> <div class="form-group"> <label for="search_txt_roleName" class="col-sm-1 control-label">角色名称</label> <div class="col-sm-11"> <input id="search_txt_roleName" type="text" class="form-control" placeholder="请输入关键字..."> </div> </div> </div> <div class="col-md-2"> <div class="form-group"> <div class="btn-group"> <button id="btn_search_save" type="button" class="btn btn-primary" title="角色查询"> <i class="fa fa-search"></i></button> <button id="btn_search_expand" type="button" class="btn btn-primary" title="面板展开"> <i class="fa fa-angle-double-up"></i></button> </div> </div> </div> </div> <div class="row" id="search_more_panel" style="display:none;"> </div> </form> </div> <div class="panel panel-gray"> <div class="panel-heading"> <h4>角色信息 </h4> <div class="options"> <div class="btn-group"> <div class="btn-group" id="table_tools_bar"> <button type="button" class="btn btn-default dropdown-toggle btn-tools" data-toggle="dropdown" title="定制列显示"><i class="fa fa-th-list"></i> <span class="caret"></span></button> </div> <button id="btn_role_refresh" type="button" class="btn btn-default btn-tools" title="角色刷新"><i class="fa fa-refresh"></i></button> </div> </div> <div class="options options-groups"> <a href="javascript:;" id="btn_role_delete" title="角色删除"><i class="fa fa-times"></i> 删除</a> <a data-toggle="modal" href="#form_modal" id="btn_role_edit" title="角色编辑"><i class="fa fa-edit"></i> 编辑</a> <a data-toggle="modal" href="#form_modal" id="btn_role_add" title="角色添加"><i class="fa fa-pencil"></i> 添加</a> </div> </div> <div class="panel-body"> <div class="table-responsive"> <table id="role_table"></table> </div> <!-- add/edit modal-begin --> <div id="form_modal" class="modal fade md-trigger" data-modal="md-fade-in-scale-up" tabindex="-1" role="dialog" aria-labelledby="form_modal_title" data-keyboard="true" data-backdrop="static" aria-hidden="true"> <div id="form_modal_dialog" class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="form_modal_title"></h4> </div> <div class="modal-body"> <form id="modalForm" class="form-horizontal" role="form" enctype="multipart/form-data"> <!-- 隐藏值存放区域 begin--> <input name="id" id="form_hidden_id" type="hidden"> <input name="createrId" id="form_hidden_createrId" type="hidden"> <!-- 隐藏值存放区域 end--> <div class="form-group"> <label for="form_txt_roleName" class="col-sm-2 control-label">角色名称</label> <div class="col-sm-7"> <input id="form_txt_roleName" name="roleName" maxlength="32" placeholder="角色名称最多32个字符" required="" type="text" class="form-control"> </div> <div class="col-sm-3"> <p class="help-block">角色名称必填!</p> </div> </div> <div class="form-group"> <label for="form_txt_roleName" class="col-sm-2 control-label">角色权限</label> <div class="col-sm-10"> <table id="table_module" class="table table-bordered"> <thead> <tr> <th width="2%" style="padding: 10px"> </th> <th width="28%" style="padding: 10px"> 模块 </th> <th width="30%" style="padding: 10px"> 功能 </th> <th width="30%" style="padding: 10px"> 动作 </th> </tr> </thead> @if (null != Model.ModuleList) { <tbody> @foreach (var module in Model.ModuleList) { if (module.Id == 1 && Model.User.UserRoleId != 1) { } else { <tr> <td> <input type="checkbox" id="power_@module.Id" name="mod_@module.Id" value="@module.Id" onclick="checkModule(@module.Id);" /> </td> <td> @module.ModuleCnName </td> <td> <table width="100%"> @if (null != module.Children) { foreach (var child in module.Children) { <tr> <td width="6%"><input type="checkbox" id="power_@child.Id" name="fun_@module.Id" value="@child.Id" onclick="checkFun(@module.Id);" /></td> <td width="94%">@child.ModuleCnName</td> </tr> } } </table> </td> <td> <table width="100%"> @if (null != module.Children) { foreach (var child in module.Children) { if (null != child.Children) { foreach (var subChild in child.Children) { <tr> <td width="6%"><input type="checkbox" id="power_@subChild.Id" name="act_@child.Id" value="@subChild.Id" onclick="checkAction(@child.Id);" /></td> <td width="94%">@subChild.ModuleCnName</td> </tr> } } } } </table> </td> </tr> } } </tbody> } </table> </div> </div> <div class="form-group"> <label for="form_txt_roleMark" class="col-sm-2 control-label"> 角色描述 </label> <div class="col-sm-10"> <textarea id="form_txt_roleMark" name="roleMark" maxlength="255" placeholder="角色描述最多255个字符" class="form-control autosize"></textarea> </div> </div> </form> </div> <div class="modal-footer"> <button id="btn_role_save" type="button" class="btn btn-primary"> 确定 </button> <button type="button" class="btn btn-default" data-dismiss="modal"> 取消 </button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- add/edit modal-end --> </div> </div> </div> </div> </div> <!-- container 内容显示区域end--> </div> <!--wrap --> </div> </div> <!-- page-container --> <!-- page-content --> @{Html.RenderPartial("Footer");} </body> </html> <script type="text/javascript" charset="utf-8" src="@Url.Content("~/Contents/backend/plugs/bootstrap-table/src/bootstrap-table.js")?v=@Model.Version"></script> <script type="text/javascript" charset="utf-8" src="@Url.Content("~/Contents/backend/plugs/bootstrap-table/src/locale/bootstrap-table-zh-CN.js")?v=@Model.Version"></script> <script type="text/javascript" charset="utf-8" src="@Url.Content("~/Contents/backend/js/sys_role.js")?v=@Model.Version"></script>
(3)业务界面逻辑 sys_role.js
/** * sys_role * 角色信息 * @author steven9801@163.com * @date 2015-11-19 */ (function ($) { $(document).ready(function () { /** * 初始化 */ init(); /** * 新建模态 */ $('#btn_role_add').click(function () { addModal() }); /** * 编辑模态 */ $('#btn_role_edit').click(function () { var rowList = dataGrid.bootstrapTable('getSelections'); var length = rowList.length; if (length == 0) { warningBox('请选择编辑对象.'); return false; } if (length > 1) { warningBox('只能编辑一项.'); return false; } editModal(rowList[0]); }); /** * 保存动作 */ $('#btn_role_save').click(function () { switch (dialogType) { case 'add': onAdd(); break; case 'edit': onEdit(); break; default: break; } }); /** * 删除 */ $('#btn_role_delete').click(function () { onDelete(); }); //-----------------常规事件----------begin-------// /** * 刷新 */ $('#btn_role_refresh').click(function () { dataGrid.bootstrapTable('destroy'); loadGrid(); }); /** * 展开 */ $('#btn_search_expand').click(function () { $(this).html(''); if (!searchStatus) { $('#search_more_panel').show('slow'); $(this).html('<i class="fa fa-angle-double-down"></i>'); searchStatus = true; } else { $('#search_more_panel').hide('slow'); $(this).html('<i class="fa fa-angle-double-up"></i>'); searchStatus = false; } return false; }); /** * 提交查询 */ $('#btn_search_save').click(function () { dataGrid.bootstrapTable('destroy'); bindGrid(function (params) { var roleName = $('#search_txt_roleName').val(); role.pageSize = params.pageSize; role.pageStart = params.pageNumber; //params.pageSize * (params.pageNumber - 1); console.info(params.pageNumber); role.sortName = params.sortName; role.sortOrder = params.sortOrder; if (roleName.length > 0) { role.roleName = roleName; } return JSON.stringify(role); }); }); //-----------------常规事件----------end-------// }); })(jQuery); /** * 全局变量 */ //--------------------------全局变量区---------------------------// var dataGrid = null; //列表对象 var dialogType = 'add'; var role = {}; var lock = false; //防止重复提交 var searchStatus = false; //查询面板状态 //--------------------------全局变量区---------------------------// /** * 初始化 */ function init() { loadGrid(); $("#form_modal .modal-body").css({ height: "650px", overflowX: "hidden", overflowY: "auto" }); $('textarea.autosize').autosize({ append: "\n" }); }; /** * * 加载列表 * */ function loadGrid() { bindGrid(function (params) { return JSON.stringify({ pageSize: params.pageSize, pageStart: params.pageNumber, //params.pageSize * (params.pageNumber - 1), sortName: params.sortName, sortOrder: params.sortOrder }); }); return false; }; /** * 绑定列表 */ function bindGrid(callBack) { dataGrid = $('#role_table').bootstrapTable({ method: 'POST', contentType: 'application/json;charset=utf-8', url: '../admin/role/list', height: 450, striped: true, pagination: true, sidePagination: 'server', pageSize: 25, pageList: [25, 50, 100, 200], showExport: true, sortName: 'createdAt', sortOrder: 'desc', minimunCountColumns: 2, formatLoadingMessage: function () { return '<img src="../Contents/backend/images/loading.gif"/>'; }, queryParams: callBack, columns: [ { field: 'state', checkbox: true }, { field: 'roleName', title: '角色名称', align: 'left', valign: 'middle', sortable: true }, { field: 'createdAt', title: '创建时间', align: 'center', valign: 'middle', sortable: true }, { field: 'operate', title: '操作', align: 'left', valign: 'middle', sortable: false, formatter: operateFormatter, events: operateEvents } ] }); }; /** * 格式化操作列 * */ function operateFormatter(value, row, index) { var content = []; content.push(' <a class="view" data-toggle="modal" href="#form_modal" title="角色查看"><i class="fa fa-eye"></i></a>'); content.push(' <a class="edit" data-toggle="modal" href="#form_modal" title="角色编辑"><i class="fa fa-edit"></i></a>'); content.push(' <a class="delete" href="javascript:void(0)" title="角色删除"><i class="fa fa-times"></i></a>'); return content.join(''); }; /** * 操作列事件 */ window.operateEvents = { 'click .view': function (e, value, row, index) { viewModal(row); return false; }, 'click .edit': function (e, value, row, index) { editModal(row); return false; }, 'click .delete': function (e, value, row, index) { if (lock) return false; lock = true; if (userToken.id != row.createrId) { lock = false; warningBox('对不起,您无权删除该角色.'); return false; } var ids = []; ids.push(row.id); var params = {}; params.ids = ids; deleteModal(params); } }; /** * 显示模态 */ function showModal(action, title, width) { dialogType = action; $('.modal-footer').show(); $('#form_modal #form_modal_title').html(title); $('#form_modal_dialog').css({ width: width }); $('select,textarea,input').prop('disabled', false); $('#back-to-top').trigger('click'); return false; }; /** * 绑定模态 */ function bindModal(row) { $('#form_hidden_id').val(row.id); $('#form_hidden_createrId').val(row.createrId); $('#form_txt_roleName').val(row.roleName); $('#form_txt_roleMark').val(row.roleMark); $("input[id^='power_']").removeAttr("checked"); var moduleIdList = row.moduleIdList; for (var i in moduleIdList) { var id = moduleIdList[i]; $("input[id='power_" + id + "']").prop("checked", true); } }; /** * 查看模态 */ function viewModal(row) { showModal('view', '角色查看', '60%'); bindModal(row); $('select,textarea,input:not(.fixed-table-container input)').prop('disabled', true); $('#search_panel select,#search_panel input').prop('disabled', false); $('#table_tools_bar').find('input').prop('disabled', false); $('.modal-footer').hide(); return false; }; /** * 编辑模态 */ function editModal(row) { role = row; if (userToken.id != row.createrId) { pauseModal('#form_modal'); warningBox('对不起,您无权编辑该角色.'); return false; } showModal('edit', '角色编辑', '60%'); bindModal(row); return false; }; /** * 新建模态 */ function addModal() { showModal('add', '角色新建', '60%'); $('input[type=text],input[type=hidden],input[type=number],textarea').val(''); $('select option').eq(0).prop('selected', true); $("input[id^='power_']").prop('checked', false); return false; }; /** * 验证表单 */ function checkForm() { if (lock) return false; lock = true; var roleName = $("#form_txt_roleName").val(); if (roleName.length == 0) { warningBox("角色名称不能为空."); lock = false; return false; } if (roleName.length > 32) { warningBox("角色名称最多32个字符."); lock = false; return false; } if ($("input[id^='power_']:checkbox:checked").length == 0) { warningBox("请选择权限."); lock = false; return false; } var roleMark = $("#form_txt_roleMark").val(); if (roleMark.length > 255) { warningBox("角色描述最多255个字符."); lock = false; return false; } var moduleIdList = []; $("input[id^='power_']:checkbox:checked").each(function () { var id = parseInt($(this).val()); moduleIdList.push(id); }); role.roleName = roleName; role.roleMark = roleMark; role.moduleIdList = moduleIdList; return true; }; /** * 角色添加 */ function onAdd() { if (!checkForm()) { return false; } $('.data-loading').show(); var task = new DelayedTask(function () { $.ajax({ cache: false, type: "POST", dataType: "json", contentType: "application/json;charset=utf-8", url: "../admin/role/add", data: JSON.stringify(role), timeout: 30000, success: function (data) { if (data) { $(".data-loading").hide(); var code = data.code; if (code != 0) { dangerBox(data.message); lock = false; return false; } lock = false; $('#form_modal').modal('hide') successBox('角色新建成功.'); $('#btn_role_refresh').trigger('click'); } return false; }, error: function (e) { if (e.status == 404) { window.location = "../error/http404"; } else if (e.status == 500) { window.location = "../error/http500"; } } }); }); task.delay(500); return false; }; /** * 角色编辑 */ function onEdit() { if (!checkForm()) { return false; } $('.data-loading').show(); var task = new DelayedTask(function () { $.ajax({ cache: false, type: "POST", dataType: "json", contentType: "application/json;charset=utf-8", url: "../admin/role/edit", data: JSON.stringify(role), timeout: 30000, success: function (data) { if (data) { $(".data-loading").hide(); var code = data.code; if (code != 0) { dangerBox(data.message); lock = false; return false; } lock = false; $('#form_modal').modal('hide') successBox('角色编辑成功.'); $('#btn_role_refresh').trigger('click'); } return false; }, error: function (e) { if (e.status == 404) { window.location = "../error/http404"; } else if (e.status == 500) { window.location = "../error/http500"; } } }); }); task.delay(500); return false; }; /** * 角色删除 */ function onDelete() { if (lock) return false; lock = true; var ids = []; var rowList = dataGrid.bootstrapTable('getSelections'); var length = rowList.length; if (length == 0) { warningBox('请选择删除对象.'); lock = false; return false; } var flag = false; for (var i in rowList) { var row = rowList[i]; var createrId = row.createrId; if (userToken.id != createrId) { flag = true; } var id = row.id; ids.push(id); } if (flag) { warningBox('对不起,您无权删除该角色.'); lock = false; return false; } var params = {}; params.ids = ids; deleteModal(ids); return false; }; /** * 删除模态 */ function deleteModal(ids) { confirmBox('您确定要删除吗?!', function (result) { if (result) { $('.data-loading').show(); $.ajax({ cache: false, type: 'POST', dataType: 'json', contentType: 'application/json;charset=utf-8', url: '../admin/role/delete', data: JSON.stringify(ids), timeout: 30000, success: function (data) { if (data) { $('.data-loading').hide(); var code = data.code; if (code != 0) { dangerBox(data.message); lock = false; return false; } lock = false; successBox('角色删除成功.'); $('#btn_role_refresh').trigger('click'); } return false; }, error: function (e) { if (e.status == 404) { window.location = "../error/http404"; } else if (e.status == 500) { window.location = "../error/http500"; } } }); } else { lock = false; } }); return false; }; /** * 选择模块 */ function checkModule(moduleId) { $("input[name='fun_" + moduleId + "']").each(function () { if ($(this).is(":checked") == true) { $(this).prop("checked", false) } else { $(this).prop("checked", true); } }); }; /** * 选择功能 */ function checkFun(moduleId) { var funLength = $("input[name='fun_" + moduleId + "']:checkbox:checked").length; if (funLength != 0) { $("input[name='mod_" + moduleId + "']").prop("checked", true); } else { $("input[name='mod_" + moduleId + "']").prop("checked", false); } }; /** * 选择动作 */ function checkAction(funId) { var actLength = $("input[name='act_" + funId + "']:checkbox:checked").length; if (actLength != 0) { $("input[id='power_" + funId + "']").prop("checked", true); } else { $("input[id='power_" + funId + "']").prop("checked", false); } };
(4)业务控制器 RoleController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Aptamil.Services; using log4net; using Aptamil.Areas.Admin.ViewModels; using Aptamil.Models; using Aptamil.Comman; namespace Aptamil.Areas.Admin.Controllers { /// <summary> /// 角色模块控制器 /// steven9801@163.com /// </summary> public class RoleController : BaseController { private static ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly RoleInfoService roleInfoService = new RoleInfoService(); private static readonly ModuleInfoService moduleInfoService = new ModuleInfoService(); private static readonly RoleModuleService roleModuleService = new RoleModuleService(); private static readonly TransactionalService transactionalService = new TransactionalService(); [SessionValidate(ActionValidate = false, Comment = "角色界面", RouteUrl = "../admin/role"), HttpGet] public ActionResult Index() { try { ModuleInfo moduleInfo = new ModuleInfo(); moduleInfo.SortName = "id"; moduleInfo.SortOrder = "desc"; List<ModuleInfo> list = moduleInfoService.SearchModuleInfo(moduleInfo); List<ModuleInfo> moduleList = this.ToObjectModuleTree(list, 0); var viewModel = new RoleViewModel { NameCn = AppSettings.NAME_CN, Keywords = AppSettings.KEYWORDS, Description = AppSettings.DESCRIPTION, Author = AppSettings.AUTHOR, User = CurrentUser ?? null, RoleModuleList = CurrentUser != null ? ToObjectRoleModuleTree(CurrentUser.RoleModuleList, 0) : null, Version = DateTimeUtils.DateTimeToLong(), ModuleList = moduleList }; return View(viewModel); } catch (Exception e) { logger.Error(e); return View("error"); } } private RoleInfo findRoleInfo(RoleInfo roleInfo) { if (roleInfo.RoleName != null) { roleInfo.RoleNameLike = true; } return roleInfo; } [SessionValidate(ActionValidate = false, Comment = "角色列表", RouteUrl = "../admin/role/list"), HttpPost] public string List(RoleInfo roleInfo) { try { RoleInfo roleInfoModel = findRoleInfo(roleInfo); int total = roleInfoService.GetRoleInfoCount(roleInfoModel); List<RoleInfo> roleList = roleInfoService.SearchRoleInfo(roleInfoModel); EntityGrid<RoleInfo> entityGrid = null; if (roleList != null && roleList.Count() > 0) { foreach (RoleInfo role in roleList) { List<int> moduleIdList = new List<int>(); RoleModule roleModule = new RoleModule(); roleModule.RoleId=role.Id; List<RoleModule> roleModuleList = roleModuleService.SearchRoleModule(roleModule); foreach (RoleModule module in roleModuleList) { moduleIdList.Add(module.ModuleId.Value); } role.ModuleIdList = moduleIdList; } entityGrid = new EntityGrid<RoleInfo>(); entityGrid.Rows = roleList; entityGrid.Total = total; } else { entityGrid = new EntityGrid<RoleInfo>(); } return this.HandlerResponseMessage(entityGrid); } catch (Exception e) { logger.Error(e); return this.HandlerFailMessage(e.Message); } } /// <summary> /// 角色新建 /// </summary> /// <param name="UserInfo"></param> /// <returns></returns> [SessionValidate(Comment = "角色新建", RouteUrl = "../admin/role/add"), HttpPost] public string Add(RoleInfo roleInfo) { try { string roleName = roleInfo.RoleName; RoleInfo model = new RoleInfo(); model.RoleName = roleName; RoleInfo roleInfoModel = roleInfoService.GetRoleInfo(model); if (roleInfoModel != null) { throw new Exception("角色名称重复."); } roleInfo.CreatedAt = DateTime.Now; roleInfo.UpdatedAt = DateTime.Now; roleInfo.CreaterId = CurrentUser.Id; int change = transactionalService.InsertRoleInfo(roleInfo); if (change == 0) { throw new Exception("角色新建失败."); } this.LogSuccess("角色新建"); return this.HandlerSuccessMessage("../admin/role"); } catch (Exception e) { this.LogFailed("角色新建"); logger.Error(e); return this.HandlerFailMessage(e.Message); } } /// <summary> /// 角色编辑 /// </summary> /// <param name="UserInfo"></param> /// <returns></returns> [SessionValidate(Comment = "角色编辑", RouteUrl = "../admin/role/edit"), HttpPost] public string Edit(RoleInfo roleInfo) { try { int change = transactionalService.UpdateRoleInfo(roleInfo); if (change == 0) { throw new Exception("角色编辑失败."); } this.LogSuccess("角色编辑"); return this.HandlerSuccessMessage("../admin/role"); } catch (Exception e) { this.LogFailed("角色编辑"); logger.Error(e); return this.HandlerFailMessage(e.Message); } } /// <summary> /// 角色删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> [SessionValidate(Comment = "角色删除", RouteUrl = "../admin/role/delete"), HttpPost] public string Delete(List<int> ids) { try { if (ids.Count() == 0) { throw new Exception("ids参数非空."); } List<RoleInfo> roleList = new List<RoleInfo>(); foreach (int id in ids) { RoleInfo roleInfo = new RoleInfo(); roleInfo.Id = id; roleList.Add(roleInfo); } int change = transactionalService.DeleteRoleInfo(roleList); if (change == 0) { throw new Exception("角色删除失败."); } this.LogSuccess("角色删除"); return this.HandlerSuccessMessage("../admin/role"); } catch (Exception e) { this.LogFailed("角色删除"); logger.Error(e); return this.HandlerFailMessage(e.Message); } } } }
(5)业务实体层 RoleInfo.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Aptamil.Models { /// <summary> /// 角色实体类 /// </summary> [Serializable] public class RoleInfo:BaseModel<RoleInfo> { /// <summary> /// 自增列/唯一主键 /// </summary> private int? id; /// <summary> /// 角色名称 /// </summary> private string roleName; /// <summary> /// 角色备注 /// </summary> private string roleMark; /// <summary> /// 记录创建者id /// </summary> private int? createrId; /// <summary> /// 记录更新时间 /// </summary> private DateTime? updatedAt; /// <summary> /// 记录创建时间 /// </summary> private DateTime? createdAt; List<int> moduleIdList; private bool? roleNameLike; [JsonProperty(PropertyName = "id")] public int? Id { get { return id; } set { id = value; } } [JsonProperty(PropertyName = "roleName")] public string RoleName { get { return roleName; } set { roleName = value; } } [JsonProperty(PropertyName = "roleMark")] public string RoleMark { get { return roleMark; } set { roleMark = value; } } [JsonProperty(PropertyName = "createrId")] public int? CreaterId { get { return createrId; } set { createrId = value; } } [JsonProperty(PropertyName = "createdAt")] public DateTime? CreatedAt { get { return createdAt; } set { createdAt = value; } } [JsonProperty(PropertyName = "updatedAt")] public DateTime? UpdatedAt { get { return updatedAt; } set { updatedAt = value; } } [JsonProperty(PropertyName = "moduleIdList")] public List<int> ModuleIdList { get { return moduleIdList; } set { moduleIdList = value; } } [JsonIgnore] public bool? RoleNameLike { get { return roleNameLike; } set { roleNameLike = value; } } } }
(6)业务数据层 RoleInfoDataProvider.cs
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using Aptamil.Models; using Aptamil.Comman; namespace Aptamil.Providers { public class RoleInfoDataProvider: BaseDataProvider { public int InsertRoleInfo(RoleInfo roleInfo) { StringBuilder commandText = new StringBuilder(); commandText.Append("insert into tb_role_info("); commandText.Append("role_name,role_mark,creater_id,updated_at,created_at)"); commandText.Append(" values ("); commandText.Append("@role_name,@role_mark,@creater_id,@updated_at,@created_at);"); SqlParameter[] parameters = { new SqlParameter("@role_name", SqlDbType.NVarChar,50), new SqlParameter("@role_mark", SqlDbType.NVarChar,255), new SqlParameter("@creater_id", SqlDbType.Int,4), new SqlParameter("@updated_at", SqlDbType.DateTime), new SqlParameter("@created_at", SqlDbType.DateTime) }; parameters[0].Value = roleInfo.RoleName; parameters[1].Value = roleInfo.RoleMark; parameters[2].Value = roleInfo.CreaterId; parameters[3].Value = roleInfo.UpdatedAt; parameters[4].Value = roleInfo.CreatedAt; int id = 0; int result = DbHelper.ExecuteNonQuery(out id, CommandType.Text,commandText.ToString(), parameters); return result > 0 ? id : 0; } public int UpdateRoleInfo(RoleInfo roleInfo) { if (roleInfo.Id == null) { throw new Exception("id参数不为空."); } RoleInfo entity = GetRoleInfo(roleInfo.Id.Value); if (entity == null) { throw new Exception("[id="+ entity.Id+"]不存在或者已被删除."); } if (!string.IsNullOrWhiteSpace(roleInfo.RoleName)) { entity.RoleName = roleInfo.RoleName; } if (!string.IsNullOrWhiteSpace(roleInfo.RoleMark)) { entity.RoleMark = roleInfo.RoleMark; } if (roleInfo.CreaterId != null) { entity.CreaterId = roleInfo.CreaterId; } if (roleInfo.UpdatedAt != null) { entity.UpdatedAt = roleInfo.UpdatedAt; } if (roleInfo.CreatedAt != null) { entity.CreatedAt = roleInfo.CreatedAt; } StringBuilder commandText = new StringBuilder(); commandText.Append("update tb_role_info set "); commandText.Append("role_name = @role_name,"); commandText.Append("role_mark = @role_mark,"); commandText.Append("creater_id = @creater_id,"); commandText.Append("updated_at = @updated_at,"); commandText.Append("created_at = @created_at"); commandText.Append(" where id = @id;"); SqlParameter[] parameters = { new SqlParameter("@role_name", SqlDbType.NVarChar,50), new SqlParameter("@role_mark", SqlDbType.NVarChar,255), new SqlParameter("@creater_id", SqlDbType.Int,4), new SqlParameter("@updated_at", SqlDbType.DateTime), new SqlParameter("@created_at", SqlDbType.DateTime), new SqlParameter("@id", SqlDbType.Int,4) }; parameters[0].Value = entity.RoleName; parameters[1].Value = entity.RoleMark; parameters[2].Value = entity.CreaterId; parameters[3].Value = entity.UpdatedAt; parameters[4].Value = entity.CreatedAt; parameters[5].Value = entity.Id; return DbHelper.ExecuteNonQuery(CommandType.Text, commandText.ToString(), parameters); } public int DeleteRoleInfo(int id) { StringBuilder commandText = new StringBuilder(); commandText.Append("delete from tb_role_info "); commandText.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,4) }; parameters[0].Value = id; return DbHelper.ExecuteNonQuery(CommandType.Text, commandText.ToString(), parameters); } public RoleInfo GetRoleInfo(int id) { StringBuilder commandText = new StringBuilder(); commandText.Append("select top 1 * from tb_role_info "); commandText.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,4) }; parameters[0].Value = id; RoleInfo entity = null; using (IDataReader reader = DbHelper.ExecuteReader(CommandType.Text, commandText.ToString(), parameters)) { while (reader.Read()) { entity = Fill(reader, null); } } return entity; } public RoleInfo GetRoleInfo(RoleInfo roleInfo) { StringBuilder whereClause = new StringBuilder(); List<SqlParameter> parameters = new List<SqlParameter>(); if (roleInfo.Id != null) { whereClause.Append(" and id = @id"); parameters.Add(CreateParameter("@id", SqlDbType.Int, roleInfo.Id)); } if (!string.IsNullOrWhiteSpace(roleInfo.RoleName)) { whereClause.Append(" and role_name = @role_name"); parameters.Add(CreateParameter("@role_name", SqlDbType.NVarChar, roleInfo.RoleName)); } if (!string.IsNullOrWhiteSpace(roleInfo.RoleMark)) { whereClause.Append(" and role_mark = @role_mark"); parameters.Add(CreateParameter("@role_mark", SqlDbType.NVarChar, roleInfo.RoleMark)); } if (roleInfo.CreaterId != null) { whereClause.Append(" and creater_id = @creater_id"); parameters.Add(CreateParameter("@creater_id", SqlDbType.Int, roleInfo.CreaterId)); } if (roleInfo.UpdatedAt != null) { whereClause.Append(" and updated_at = @updated_at"); parameters.Add(CreateParameter("@updated_at", SqlDbType.DateTime, roleInfo.UpdatedAt)); } if (roleInfo.CreatedAt != null) { whereClause.Append(" and created_at = @created_at"); parameters.Add(CreateParameter("@created_at", SqlDbType.DateTime, roleInfo.CreatedAt)); } string processedWhereClause = ProcessWhereClause(whereClause.ToString()); StringBuilder commandText = new StringBuilder(); commandText.AppendFormat("select top 1 * from tb_role_info {0}", processedWhereClause); RoleInfo entity = null; using (IDataReader reader = DbHelper.ExecuteReader(CommandType.Text, commandText.ToString(), parameters.ToArray())) { while (reader.Read()) { entity = Fill(reader, null); } } return entity; } public RoleInfo Fill(IDataReader reader, RoleInfo entity) { if (entity == null) entity = new RoleInfo(); for (int i = 0; i < reader.FieldCount; i++) { switch (reader.GetName(i)) { case "id": entity.Id = int.Parse(reader[i].ToString()); break; case "role_name": entity.RoleName = reader[i].ToString(); break; case "role_mark": entity.RoleMark = reader[i].ToString(); break; case "creater_id": entity.CreaterId = int.Parse(reader[i].ToString()); break; case "updated_at": entity.UpdatedAt = DateTime.Parse(reader[i].ToString()); break; case "created_at": entity.CreatedAt = DateTime.Parse(reader[i].ToString()); break; } } return entity; } public int GetRoleInfoCount(RoleInfo roleInfo) { StringBuilder whereClause = new StringBuilder(); List<SqlParameter> parameters = new List<SqlParameter>(); if (roleInfo.Id != null) { whereClause.Append(" and id = @id"); parameters.Add(CreateParameter("@id", SqlDbType.Int, roleInfo.Id)); } if (!string.IsNullOrWhiteSpace(roleInfo.RoleName)) { if (roleInfo.RoleNameLike.Value) { whereClause.Append(" and role_name like @role_name"); parameters.Add(CreateParameter("@role_name", SqlDbType.NVarChar, "%" + roleInfo.RoleName + "%")); } else { whereClause.Append(" and role_name = @role_name"); parameters.Add(CreateParameter("@role_name", SqlDbType.NVarChar, roleInfo.RoleName)); } } if (!string.IsNullOrWhiteSpace(roleInfo.RoleMark)) { whereClause.Append(" and role_mark = @role_mark"); parameters.Add(CreateParameter("@role_mark", SqlDbType.NVarChar, roleInfo.RoleMark)); } if (roleInfo.CreaterId != null) { whereClause.Append(" and creater_id = @creater_id"); parameters.Add(CreateParameter("@creater_id", SqlDbType.Int, roleInfo.CreaterId)); } if (roleInfo.UpdatedAt != null) { whereClause.Append(" and updated_at = @updated_at"); parameters.Add(CreateParameter("@updated_at", SqlDbType.DateTime, roleInfo.UpdatedAt)); } if (roleInfo.CreatedAt != null) { whereClause.Append(" and created_at = @created_at"); parameters.Add(CreateParameter("@created_at", SqlDbType.DateTime, roleInfo.CreatedAt)); } string processedWhereClause = ProcessWhereClause(whereClause.ToString()); StringBuilder commandText = new StringBuilder(); commandText.AppendFormat("select count(0) from tb_role_info {0}", processedWhereClause); object result = DbHelper.ExecuteScalar(CommandType.Text, commandText.ToString(), parameters.ToArray()); if (result == null) { return 0; } else { return Convert.ToInt32(result); } } public List<RoleInfo> SelectRoleInfoByList(List<int> ids) { StringBuilder commandText = new StringBuilder("select * from tb_role_info where 1=1"); if (ids != null && ids.Count > 0) { commandText.Append(" and id in (" + String.Join(",", ids.ToArray()) + ")"); } List<RoleInfo> list = new List<RoleInfo>(); using (IDataReader reader = DbHelper.ExecuteReader(CommandType.Text, commandText.ToString())) { while (reader.Read()) { list.Add(Fill(reader, null)); } } return list; } public List<RoleInfo> SearchRoleInfo(RoleInfo roleInfo) { StringBuilder whereClause = new StringBuilder(); List<SqlParameter> parameters = new List<SqlParameter>(); if (roleInfo.Id != null) { whereClause.Append(" and id = @id"); parameters.Add(CreateParameter("@id", SqlDbType.Int, roleInfo.Id)); } if (!string.IsNullOrWhiteSpace(roleInfo.RoleName)) { if (roleInfo.RoleNameLike.Value) { whereClause.Append(" and role_name like @role_name"); parameters.Add(CreateParameter("@role_name", SqlDbType.NVarChar, "%" + roleInfo.RoleName + "%")); } else { whereClause.Append(" and role_name = @role_name"); parameters.Add(CreateParameter("@role_name", SqlDbType.NVarChar, roleInfo.RoleName)); } } if (!string.IsNullOrWhiteSpace(roleInfo.RoleMark)) { whereClause.Append(" and role_mark = @role_mark"); parameters.Add(CreateParameter("@role_mark", SqlDbType.NVarChar, roleInfo.RoleMark)); } if (roleInfo.CreaterId != null) { whereClause.Append(" and creater_id = @creater_id"); parameters.Add(CreateParameter("@creater_id", SqlDbType.Int, 4)); } if (roleInfo.UpdatedAt != null) { whereClause.Append(" and updated_at = @updated_at"); parameters.Add(CreateParameter("@updated_at", SqlDbType.DateTime, roleInfo.UpdatedAt)); } if (roleInfo.CreatedAt != null) { whereClause.Append(" and created_at = @created_at"); parameters.Add(CreateParameter("@created_at", SqlDbType.DateTime, roleInfo.CreatedAt)); } if (roleInfo.PageStart != null && roleInfo.PageSize != null) { whereClause.AppendFormat(" and num {0}", ProcessPaging(roleInfo.PageStart.Value, roleInfo.PageSize.Value)); } string processedWhereClause = ProcessWhereClause(whereClause.ToString()); StringBuilder commandText = new StringBuilder(); commandText.AppendFormat("select* from (select *, row_number() over(order by id) num from tb_role_info) a {0}", processedWhereClause); if (roleInfo.SortName != null && roleInfo.SortOrder != null) { commandText.AppendFormat(" order by {0} {1}", roleInfo.SortName.ToUnderline(), roleInfo.SortOrder.ToUnderline()); } string sql = commandText.ToString(); List<RoleInfo> list = new List<RoleInfo>(); using (IDataReader reader = DbHelper.ExecuteReader(CommandType.Text, commandText.ToString(), parameters.ToArray())) { while (reader.Read()) { list.Add(Fill(reader, null)); } } return list; } } }
(7)业务服务层 RoleInfoService.cs
using System.Collections.Generic; using Aptamil.Models; using Aptamil.Providers; namespace Aptamil.Services { /// <summary> /// 角色服务类 /// </summary> public class RoleInfoService : BaseService { private static readonly RoleInfoDataProvider roleInfoDataProvider = new RoleInfoDataProvider(); public int InsertRoleInfo(RoleInfo roleInfo) { return roleInfoDataProvider.InsertRoleInfo(roleInfo); } public RoleInfo GetRoleInfo(int id) { return roleInfoDataProvider.GetRoleInfo(id); } public RoleInfo GetRoleInfo(RoleInfo roleInfo) { return roleInfoDataProvider.GetRoleInfo(roleInfo); } public int UpdateRoleInfo(RoleInfo roleInfo) { return roleInfoDataProvider.UpdateRoleInfo(roleInfo); } public int DeleteRoleInfo(int id) { return roleInfoDataProvider.DeleteRoleInfo(id); } public int GetRoleInfoCount(RoleInfo roleInfo) { return roleInfoDataProvider.GetRoleInfoCount(roleInfo); } public List<RoleInfo> SelectRoleInfoByList(List<int> ids) { return roleInfoDataProvider.SelectRoleInfoByList(ids); } public List<RoleInfo> SearchRoleInfo(RoleInfo roleInfo) { return roleInfoDataProvider.SearchRoleInfo(roleInfo); } } }
就这样简单整个业务表的CRUD结构清晰的完整的呈现在你面前啦。管中窥豹,真正拥有者会如获至宝。
到此:
全部主流web开发语言之主流web开发框架实战化项目之三板斧系列全部结束,我只想证明一点语言不是问题思路真是相通的,
学好一门面向对象语言对付其他的那都不是个事,直接套用思路翻译业务简称套路。
感兴趣的朋友扫下面的二维码给点打赏吧!
虽功未成,亦未敢藏私,众侠诸神通尽录于此,竟成一笈,名葵花宝典,以飨后世。
邮箱:steven9801@163.com
QQ: 48039387
邮箱:steven9801@163.com
QQ: 48039387