基于.net EF6 MVC5+WEB Api 的Web系统框架总结(2)-业务项目搭建
程序员文章站
2022-07-04 23:36:02
本节将介绍如何进行业务项目搭建。 本业务项目示例是简单的企业信息管理功能,业务项目采用Code First方式,搭建包括: 搭建完项目效果: 1、创建实体项目-ShiQuan.Company.Entity 创建企业信息实体 示例中企业信息包括:编号、名称、负责人、联系人、联系电话、联系地址等 2、创 ......
本节将介绍如何进行业务项目搭建。
本业务项目示例是简单的企业信息管理功能,业务项目采用code first方式,搭建包括:
- 创建实体项目
- 创建实体数据表映射
- 创建业务处理项目
- 创建业务web项目
搭建完项目效果:
1、创建实体项目-shiquan.company.entity
创建企业信息实体
示例中企业信息包括:编号、名称、负责人、联系人、联系电话、联系地址等
using system; using system.collections.generic; using system.componentmodel.dataannotations; using system.linq; using system.text; using system.threading.tasks; namespace shiquan.company.entity { /// <summary> /// 企业信息 /// </summary> public class companyinfoentity:basiccompanyentity { /// <summary> /// 编号 /// </summary> [display(name = "编号"), maxlength(50)] public string code { get; set; } /// <summary> /// 编号 /// </summary> [display(name = "编号"), maxlength(100)] public string name { get; set; } /// <summary> /// 负责人 /// </summary> [display(name = "负责人"), maxlength(50)] public string leader { get; set; } /// <summary> /// 联系人 /// </summary> [display(name = "联系人"), maxlength(50)] public string linkman { get; set; } /// <summary> /// 联系电话 /// </summary> [display(name = "联系电话"), maxlength(50)] public string phone { get; set; } /// <summary> /// 联系地址 /// </summary> [display(name = "联系地址"), maxlength(255)] public string address { get; set; } /// <summary> /// 备注说明 /// </summary> [display(name = "备注说明"), maxlength(255)] public string remark { get; set; } } }
2、创建实体数据表映射项目-shiquan.company.mapping
创建空数据库
创建项目
创建企业信息数据表映射
using shiquan.company.entity; using system; using system.collections.generic; using system.data.entity.modelconfiguration; using system.linq; using system.text; using system.threading.tasks; namespace shiquan.company.mapping { /// <summary> /// 实体数据映射 /// </summary> public class companyinfomap : entitytypeconfiguration<companyinfoentity> { public companyinfomap() { #region 表、主键 //表 this.totable("companyinfo"); //主键 this.haskey(t => t.id); #endregion #region 配置关系 #endregion } } }
创建实体数据库上下文
选择空code first 模型
namespace shiquan.company.mapping { using system; using system.data.entity; using system.data.entity.modelconfiguration.conventions; using system.linq; public class companydbcontext : dbcontext { //您的上下文已配置为从您的应用程序的配置文件(app.config 或 web.config) //使用“companydbcontext”连接字符串。默认情况下,此连接字符串针对您的 localdb 实例上的 //“shiquan.company.mapping.companydbcontext”数据库。 // //如果您想要针对其他数据库和/或数据库提供程序,请在应用程序配置文件中修改“companydbcontext” //连接字符串。 public companydbcontext() : base("name=companydbcontext") { } //为您要在模型中包含的每种实体类型都添加 dbset。有关配置和使用 code first 模型 //的详细信息,请参阅 http://go.microsoft.com/fwlink/?linkid=390109。 // public virtual dbset<myentity> myentities { get; set; } /// <summary> /// 重写数据型号创建,添加企业信息数据表映射 /// </summary> /// <param name="modelbuilder"></param> protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.conventions.remove<pluralizingtablenameconvention>(); modelbuilder.configurations.add(new companyinfomap()); base.onmodelcreating(modelbuilder); } } }
配置数据库连接
<connectionstrings> <add name="companydbcontext" connectionstring="server=127.0.0.1;initial catalog=vsd_companydb;user id=sa;password=123456*a" providername="system.data.sqlclient" /> </connectionstrings>
配置数据库上下文允许进行更新升级
using system; using system.collections.generic; using system.data.entity.migrations; using system.linq; using system.text; using system.threading.tasks; namespace shiquan.company.mapping.migrations { internal sealed class configuration : dbmigrationsconfiguration<companydbcontext> { public configuration() { //配置允许数据库更新升级 automaticmigrationsenabled = true; automaticmigrationdatalossallowed = true; } protected override void seed(companydbcontext dbcontext) { } } }
使用update-database 对数据库进行升级更新
3、创建企业信息管理业务处理项目-shiquan.company.business
创建企业信息库业务处理基础类,实现实体查询、删除和保存功能。
using learun.database.repository; using learun.util; using shiquan.company.entity; using system; using system.collections.generic; using system.configuration; using system.data; using system.linq; using system.linq.expressions; using system.text; using system.threading.tasks; namespace shiquan.company.business { /// <summary> /// 企业信息管理库业务处理基础类 /// </summary> /// <typeparam name="t"></typeparam> public class basiccompanybll<t> : repositoryfactory<t> where t : class,new() { protected string dbconn = ""; /// <summary> /// 构造函数 /// </summary> public basiccompanybll() { //this.dbconn = configurationmanager.connectionstrings["companydbcontext"].connectionstring; this.dbconn = "companydbcontext"; } #region 获取数据 /// <summary> /// 获取列表 /// </summary> /// <param name="pagination">分页</param> /// <param name="queryjson">查询参数</param> /// <returns>返回分页列表</returns> public virtual ienumerable<t> getpagelist(pagination pagination, string queryjson) { var expression = linqextensions.true<t>(); expression = querystringtoexpression(expression, queryjson); return this.baserepository(dbconn).findlist(expression, pagination); } /// <summary> /// 获取列表 /// </summary> /// <param name="pagination">分页</param> /// <param name="queryjson">查询参数</param> /// <returns>返回分页列表</returns> public virtual ienumerable<t> getpagelist(pagination pagination, expression<func<t, bool>> linq) { return this.baserepository(dbconn).findlist(linq, pagination); } /// <summary> /// 获取列表 /// </summary> /// <param name="queryjson">查询参数</param> /// <returns>返回列表</returns> public virtual ienumerable<t> getlist(string queryjson) { var expression = linqextensions.true<t>(); expression = querystringtoexpression(expression, queryjson); return this.baserepository(dbconn).iqueryable(expression); } /// <summary> /// 获取列表 /// </summary> /// <param name="queryjson">查询参数</param> /// <returns>返回列表</returns> public virtual iqueryable<t> getlist(expression<func<t, bool>> linq) { return this.baserepository(dbconn).iqueryable(linq); } /// <summary> /// 获取实体 /// </summary> /// <param name="keyvalue">主键值</param> /// <returns></returns> public virtual t getentity(string keyvalue) { return this.baserepository(dbconn).findentity(keyvalue); } /// <summary> /// 根据条件获取实体 /// </summary> /// <param name="linq">linq条件</param> /// <returns></returns> public virtual t findentity(expression<func<t, bool>> linq) { return this.baserepository(dbconn).findentity(linq); } /// <summary> /// 获取数据 /// </summary> /// <param name="queryjson"></param> /// <returns></returns> public virtual datatable gettable(string queryjson) { string sql = getsql(queryjson); return this.baserepository(dbconn).findtable(sql); } /// <summary> /// 获取数据 /// </summary> /// <param name="sql"></param> /// <returns></returns> public virtual datatable gettablebysql(string sql) { //string sql = getsql(queryjson); return this.baserepository(dbconn).findtable(sql); } /// <summary> /// 获取分页列表,返回datatable /// </summary> /// <param name="queryjson">查询参数</param> /// <returns>返回列表</returns> public virtual datatable getpagetable(pagination pagination, string queryjson) { string sql = getsql(queryjson); return this.baserepository(dbconn).findtable(sql, pagination); } /// <summary> /// 获取分页列表,返回datatable /// </summary> /// <param name="sql">查询参数</param> /// <returns>返回列表</returns> public virtual datatable getpagetablebysql(pagination pagination, string sql) { //string sql = getsql(queryjson); return this.baserepository(dbconn).findtable(sql, pagination); } #endregion #region 提交数据 /// <summary> /// 删除数据 /// </summary> /// <param name="keyvalue">主键</param> public virtual void removeform(string keyvalue) { string[] dels = keyvalue.split(','); if (dels.length > 1) { irepository db = new repositoryfactory().baserepository(dbconn).begintrans(); try { foreach (var item in dels) { db.delete(item); } db.commit(); } catch (exception) { db.rollback(); throw; } } else { this.baserepository(dbconn).delete(keyvalue); } } /// <summary> /// 保存表单(新增、修改) /// </summary> /// <param name="keyvalue">主键值</param> /// <param name="entity">实体对象</param> /// <returns></returns> public virtual void saveform(string keyvalue, t entity) { if (!string.isnullorempty(keyvalue)) { this.baserepository(dbconn).update(entity); } else { this.baserepository(dbconn).insert(entity); } } #endregion #region 帮助函数 /// <summary> /// 生成查询表达式 /// </summary> /// <param name="queryjson">查询对象</param> /// <returns></returns> protected virtual expression<func<t, bool>> querystringtoexpression(expression<func<t, bool>> expression, string queryjson) { if (string.isnullorempty(queryjson)) return expression; var queryparam = queryjson.tojobject(); if (!queryparam["condition"].isempty() && !queryparam["keyword"].isempty()) { string condition = queryparam["condition"].tostring(); string keyword = queryparam["keyword"].tostring(); switch (condition) { default: break; } } return expression; } /// <summary> /// 根据实体生成sql /// </summary> /// <param name="queryjson">查询对象</param> /// <returns></returns> protected virtual string getsql(string queryjson) { stringbuilder sb = new stringbuilder(); var queryparam = queryjson.tojobject(); if (!queryparam["condition"].isempty() && !queryparam["keyword"].isempty()) { string condition = queryparam["condition"].tostring(); string keyword = queryparam["keyword"].tostring(); sb.append(" and " + condition + " like '%" + keyword + "%'"); } return sb.tostring(); } #endregion } }
创建企业信息业务处理类,继承基础业务处理类,重写保存、过滤条件方法。
using shiquan.company.entity; using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using system.linq.expressions; using learun.util; using learun.util.operat; namespace shiquan.company.business { /// <summary> /// 实现企业信息管理业务处理,继承企业信息库基础业务处理 /// </summary> public class companyinfobll : basiccompanybll<companyinfoentity> { /// <summary> /// 数据保存 /// </summary> /// <param name="keyvalue"></param> /// <param name="entity"></param> public override void saveform(string keyvalue, companyinfoentity entity) { try { if (string.isnullorempty(keyvalue)) { entity.id = guid.newguid().tostring(); } else entity.id = keyvalue; base.saveform(keyvalue, entity); } catch (exception ex) { throw; } } /// <summary> /// 重写查询过滤条件 /// </summary> /// <param name="expression"></param> /// <param name="queryjson"></param> /// <returns></returns> protected override expression<func<companyinfoentity, bool>> querystringtoexpression(expression<func<companyinfoentity, bool>> expression, string queryjson) { if (string.isnullorempty(queryjson)) return expression; var queryparam = queryjson.tojobject(); if (queryparam["code"].isempty() == false) { string keyword = queryparam["code"].tostring(); expression = expression.and(my => my.code == keyword); } if (!queryparam["condition"].isempty() && !queryparam["keyword"].isempty()) { string condition = queryparam["condition"].tostring(); string keyword = queryparam["keyword"].tostring(); switch (condition) { default: break; } } return expression; } } }
4、创建企业信息管理web项目-shiquan.company.web
创建空的企业信息管理控制器,实现列表、编辑视图,数据查询、删除、保存方法。
using learun.application.web; using learun.util; using shiquan.company.business; using shiquan.company.entity; using system; using system.collections.generic; using system.linq; using system.web; using system.web.mvc; namespace shiquan.company.web.areas.companymanage.controllers { /// <summary> /// 企业信息管理 /// </summary> public class companyinfocontroller : mvccontrollerbase { // get: companymanage/companyinfo companyinfobll service = new companyinfobll(); /// <summary> /// 列表视图 /// </summary> /// <returns></returns> public actionresult companyinfoindex() { return view(); } /// <summary> /// 编辑视图 /// </summary> /// <returns></returns> public actionresult companyinfoform() { return view(); } #region 获取数据 /// <summary> /// 获取列表 /// </summary> /// <param name="pagination">分页参数</param> /// <param name="queryjson">查询参数</param> /// <returns>返回分页列表json</returns> [httpget] public actionresult getpagelistjson(string pagination, string queryjson) { pagination paginationobj = pagination.toobject<pagination>(); var watch = commonhelper.timerstart(); var data = service.getpagelist(paginationobj, queryjson); var jsondata = new { rows = data, total = paginationobj.total, page = paginationobj.page, records = paginationobj.records, costtime = commonhelper.timerend(watch) }; //return tojsonresult(jsondata); return success(jsondata); } /// <summary> /// 获取列表 /// </summary> /// <param name="queryjson">查询参数</param> /// <returns>返回列表json</returns> [httpget] public actionresult getlistjson(string queryjson) { var data = service.getlist(queryjson); return tojsonresult(data); } /// <summary> /// 获取实体 /// </summary> /// <param name="keyvalue">主键值</param> /// <returns>返回对象json</returns> [httpget] public actionresult getformjson(string keyvalue) { var data = service.getentity(keyvalue); return tojsonresult(data); } #endregion #region 提交数据 /// <summary> /// 删除数据 /// </summary> /// <param name="keyvalue">主键值</param> /// <returns></returns> [httppost] [validateantiforgerytoken] [ajaxonly] public actionresult removeform(string keyvalue) { service.removeform(keyvalue); return success("删除成功。"); } /// <summary> /// 保存表单(新增、修改) /// </summary> /// <param name="keyvalue">主键值</param> /// <param name="entity">实体对象</param> /// <returns></returns> [httppost] [validateantiforgerytoken] [ajaxonly] public actionresult saveform(string keyvalue, companyinfoentity entity) { service.saveform(keyvalue, entity); return success("操作成功。", entity); } #endregion } }
创建列表界面
@{ viewbag.title = "客户管理"; layout = "~/views/shared/_index.cshtml"; } <div class="lr-layout"> <div class="lr-layout-center"> <div class="lr-layout-wrap lr-layout-wrap-notitle"> <div class="lr-layout-tool"> <div class="lr-layout-tool-left"> <div class="lr-layout-tool-item"> <input id="txt_keyword" type="text" class="form-control" placeholder="请输查询关键字" /> </div> <div class="lr-layout-tool-item"> <a id="btn_search" class="btn btn-primary btn-sm"><i class="fa fa-search"></i> <span class="lrlg">查询</span></a> </div> </div> <div class="lr-layout-tool-right"> <div class="btn-group btn-group-sm"> <a id="btnreload" class="btn btn-default"><i class="fa fa-refresh"></i></a> </div> <div class="btn-group btn-group-sm" learun-authorize="yes"> <a id="btnadd" class="btn btn-default"><i class="fa fa-plus"></i> <span class="lrlg">新增</span></a> <a id="btnedit" class="btn btn-default"><i class="fa fa-pencil-square-o"></i> <span class="lrlg">编辑</span></a> <a id="btndelete" class="btn btn-default"><i class="fa fa-trash-o"></i> <span class="lrlg">删除</span></a> </div> </div> </div> <div class="lr-layout-body" id="gridtable"></div> </div> </div> </div> <script type="text/javascript"> var refreshgirddata; // 更新数据 var selectedrow; var bootstrap = function ($, learun) { "use strict"; var page = { init: function () { page.initgrid(); page.bind(); }, bind: function () { // 查询 $('#btn_search').on('click', function () { var keyword = $('#txt_keyword').val(); page.search({ keyword: keyword }); }); // 刷新 $('#btnreload').on('click', function () { location.reload(); }); // 新增 $('#btnadd').on('click', function () { selectedrow = null;//新增前请清空已选中行 learun.layerform({ id: 'form', title: '新增客户', url: top.$.rooturl + '/companymanage/companyinfo/companyinfoform', width: 600, height: 400, maxmin: true, callback: function (id) { return top[id].acceptclick(refreshgirddata); } }); }); // 编辑 $('#btnedit').on('click', function () { selectedrow = $('#gridtable').jfgridget('rowdata'); var keyvalue = $('#gridtable').jfgridvalue('id'); if (learun.checkrow(keyvalue)) { learun.layerform({ id: 'form', title: '编辑客户', url: top.$.rooturl + '/companymanage/companyinfo/companyinfoform', width: 600, height: 400, maxmin: true, callback: function (id) { return top[id].acceptclick(refreshgirddata); } }); } }); // 删除 $('#btndelete').on('click', function () { var keyvalue = $('#gridtable').jfgridvalue('id'); if (learun.checkrow(keyvalue)) { learun.layerconfirm('是否确认删除该项!', function (res) { if (res) { learun.deleteform(top.$.rooturl + '/companymanage/companyinfo/deleteform', { keyvalue: keyvalue }, function () { refreshgirddata(); }); } }); } }); }, initgrid: function () { $('#gridtable').jfgrid({ url: top.$.rooturl + '/companymanage/companyinfo/getpagelistjson', headdata: [ { label: '编号', name: 'code', width: 100, align: 'left' }, { label: '名称', name: 'name', width: 200, align: 'left' }, { label: '负责人', name: 'leader', width: 100, align: 'left' }, { label: '联系人', name: 'linkman', width: 100, align: 'left' }, { label: '联系电话', name: 'phone', width: 100, align: 'left' }, { label: '联系地址', name: 'address', width: 200, align: 'left' }, { label: "最后更新", name: "modifydate", width: 140, align: "left", formatter: function (cellvalue) { return learun.formatdate(cellvalue, 'yyyy-mm-dd hh:mm'); } }, { label: '备注', name: 'remark', width: 200, align: 'left' }, ], mainid: 'id', reloadselected: true, ispage: true, sidx: 'code' }); page.search(); }, search: function (param) { $('#gridtable').jfgridset('reload', param); } }; // 保存数据后回调刷新 refreshgirddata = function () { page.search(); } page.init(); } </script>
创建编辑界面
@{ viewbag.title = "客户添加"; layout = "~/views/shared/_form.cshtml"; } <div class="lr-form-wrap" id="form"> <div class="col-xs-12 lr-form-item"> <div class="lr-form-item-title">编号<font face="宋体">*</font></div> <input id="code" type="text" class="form-control" isvalid="yes" checkexpession="notnull" /> </div> <div class="col-xs-12 lr-form-item"> <div class="lr-form-item-title">名称<font face="宋体">*</font></div> <input id="name" type="text" class="form-control" isvalid="yes" checkexpession="notnull" /> </div> <div class="col-xs-12 lr-form-item"> <div class="lr-form-item-title">负责人<font face="宋体">*</font></div> <input id="leader" type="text" class="form-control" isvalid="yes" checkexpession="notnull" /> </div> <div class="col-xs-12 lr-form-item"> <div class="lr-form-item-title">联系人</div> <input id="linkman" type="text" class="form-control" isvalid="no" checkexpession="notnull" /> </div> <div class="col-xs-12 lr-form-item"> <div class="lr-form-item-title">联系电话</div> <input id="phone" type="text" class="form-control" /> </div> <div class="col-xs-12 lr-form-item"> <div class="lr-form-item-title">联系地址</div> <input id="address" type="text" class="form-control" /> </div> <div class="col-xs-12 lr-form-item"> <div class="lr-form-item-title">备注</div> <textarea id="remark" class="form-control" style="height: 50px;"></textarea> </div> </div> <script type="text/javascript"> var acceptclick; var keyvalue = ''; var bootstrap = function ($, learun) { "use strict"; var selectedrow = learun.frametab.currentiframe().selectedrow; var page = { init: function () { page.bind(); page.initdata(); }, bind: function () { // 客户级别 //$('#f_custlevelid').lrdataitemselect({ code: 'client_level', maxheight: 230 }); //// 客户类别 //$('#f_custtypeid').lrdataitemselect({ code: 'client_sort', maxheight: 230 }); //// 客户程度 //$('#f_custdegreeid').lrdataitemselect({ code: 'client_degree', maxheight: 230 }); ////跟进人员 //$('#f_traceuserid').lrformselect({ // layerurl: top.$.rooturl + '/lr_organizationmodule/user/selectform', // layerurlw: 800, // layerurlh: 520, // dataurl: top.$.rooturl + '/lr_organizationmodule/user/getlistbyuserids' //}); ////公司行业 //$('#f_custindustryid').lrdataitemselect({ code: 'client_trade', maxheight: 230 }); }, initdata: function () { if (!!selectedrow) { keyvalue = selectedrow.id; $('#form').lrsetformdata(selectedrow); } } }; // 保存数据 acceptclick = function (callback) { if (!$('#form').lrvalidform()) { return false; } var postdata = $('#form').lrgetformdata(keyvalue); $.lrsaveform(top.$.rooturl + '/companymanage/companyinfo/saveform?keyvalue=' + keyvalue , postdata , function (res) { // 保存成功后才回调 if (!!callback) { callback(); } }); }; page.init(); } </script>
业务项目,至此搭建完成,接下来,使用web项目进行引用,
配置业务项目数据表映射
<!-- 实体类映射库名称 --> <add key="datamapper" value="learun.application.mapping.dll,shiquan.company.mapping.dll"/>
配置业务项目数据库连接,添加配置功能菜单
运行系统效果
更多精彩,且听下回分解!
上一篇: 影响MySQL的性能(一)磁盘的选择
下一篇: 在cnetos7上搭建mysql主从服务