本节将介绍如何进行业务项目搭建。
本业务项目示例是简单的企业信息管理功能,业务项目采用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', 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', 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', 100, align: 'left' }, { label: '名称', name: 'Name', 200, align: 'left' }, { label: '负责人', name: 'Leader', 100, align: 'left' }, { label: '联系人', name: 'Linkman', 100, align: 'left' }, { label: '联系电话', name: 'Phone', 100, align: 'left' }, { label: '联系地址', name: 'Address', 200, align: 'left' }, { label: "最后更新", name: "ModifyDate", 140, align: "left", formatter: function (cellvalue) { return learun.formatDate(cellvalue, 'yyyy-MM-dd hh:mm'); } }, { label: '备注', name: 'Remark', 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"/>
配置业务项目数据库连接,添加配置功能菜单
运行系统效果
更多精彩,且听下回分解!