本節將介紹如何進行業務項目搭建。 本業務項目示例是簡單的企業信息管理功能,業務項目採用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=