博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
asp.net mvc 实战化项目之三板斧
阅读量:6121 次
发布时间:2019-06-21

本文共 39399 字,大约阅读时间需要 131 分钟。

接上文希望从一张表(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;}    @{Html.RenderPartial("Header");}    
@{Html.RenderPartial("Navbar");}
@{Html.RenderPartial("Menu");}

角色信息

@{Html.RenderPartial("Footer");}

 (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('');                searchStatus = true;            }            else {                $('#search_more_panel').hide('slow');                $(this).html('');                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 '';        },        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(' ');    content.push(' ');    content.push(' ');    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{    ///     /// 角色模块控制器    /// steven9801@163.com    ///     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
list = moduleInfoService.SearchModuleInfo(moduleInfo); List
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
roleList = roleInfoService.SearchRoleInfo(roleInfoModel); EntityGrid
entityGrid = null; if (roleList != null && roleList.Count() > 0) { foreach (RoleInfo role in roleList) { List
moduleIdList = new List
(); RoleModule roleModule = new RoleModule(); roleModule.RoleId=role.Id; List
roleModuleList = roleModuleService.SearchRoleModule(roleModule); foreach (RoleModule module in roleModuleList) { moduleIdList.Add(module.ModuleId.Value); } role.ModuleIdList = moduleIdList; } entityGrid = new EntityGrid
(); entityGrid.Rows = roleList; entityGrid.Total = total; } else { entityGrid = new EntityGrid
(); } return this.HandlerResponseMessage(entityGrid); } catch (Exception e) { logger.Error(e); return this.HandlerFailMessage(e.Message); } } ///
/// 角色新建 /// ///
///
[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); } } ///
/// 角色编辑 /// ///
///
[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); } } ///
/// 角色删除 /// ///
///
[SessionValidate(Comment = "角色删除", RouteUrl = "../admin/role/delete"), HttpPost] public string Delete(List
ids) { try { if (ids.Count() == 0) { throw new Exception("ids参数非空."); } List
roleList = new List
(); 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{    ///     /// 角色实体类    ///     [Serializable]    public class RoleInfo:BaseModel
{ ///
/// 自增列/唯一主键 /// private int? id; ///
/// 角色名称 /// private string roleName; ///
/// 角色备注 /// private string roleMark; ///
/// 记录创建者id /// private int? createrId; ///
/// 记录更新时间 /// private DateTime? updatedAt; ///
/// 记录创建时间 /// private DateTime? createdAt; List
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
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
parameters = new List
(); 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
parameters = new List
(); 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
SelectRoleInfoByList(List
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
list = new List
(); using (IDataReader reader = DbHelper.ExecuteReader(CommandType.Text, commandText.ToString())) { while (reader.Read()) { list.Add(Fill(reader, null)); } } return list; } public List
SearchRoleInfo(RoleInfo roleInfo) { StringBuilder whereClause = new StringBuilder(); List
parameters = new List
(); 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
list = new List
(); 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{    ///     /// 角色服务类    ///     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
SelectRoleInfoByList(List
ids) { return roleInfoDataProvider.SelectRoleInfoByList(ids); } public List
SearchRoleInfo(RoleInfo roleInfo) { return roleInfoDataProvider.SearchRoleInfo(roleInfo); } }}

就这样简单整个业务表的CRUD结构清晰的完整的呈现在你面前啦。管中窥豹,真正拥有者会如获至宝。

到此:

全部主流web开发语言之主流web开发框架实战化项目之三板斧系列全部结束,我只想证明一点语言不是问题思路真是相通的,

学好一门面向对象语言对付其他的那都不是个事,直接套用思路翻译业务简称套路。

感兴趣的朋友扫下面的二维码给点打赏吧!

                  

转载于:https://www.cnblogs.com/fx2008/p/6082560.html

你可能感兴趣的文章
在linux中添加ftp用户,以及修改FTP默认端口号
查看>>
N26-第一周作业
查看>>
4月11日中高项作业
查看>>
华为交换机AAA特性与思科ACS对接
查看>>
二:Unit 8
查看>>
TortoiseSVN客户端重新设置用户名和密码
查看>>
nagios邮件报警配置
查看>>
Java 生产条形码代码
查看>>
python web开发-flask连接sqlite数据库
查看>>
Zxing二维码扫描
查看>>
MMU的作用
查看>>
Ubuntu环境下 matplotlib 图例中文乱码
查看>>
PostgreSQL--杀死已挂掉的连接
查看>>
决心书
查看>>
sendmail 安装配置与使用
查看>>
文件描述符和df的一个有趣的问题
查看>>
01月09日 四周二次
查看>>
计算机网络(2)
查看>>
14.4-14.5 NFS的exportfs命令,NFS客户端问题
查看>>
大型网站架构之千万PV之RabbitMQ
查看>>