dotnetcore+vue+elementUI 前后端分离架 二(后端篇)
前言
最近幾年前后端分離架構(gòu)大行其道,而且各種框架也是層出不窮。本文通過(guò)dotnetcore +vue 來(lái)介紹 前后端分離架構(gòu)實(shí)戰(zhàn)。
涉及的技術(shù)棧
服務(wù)端技術(shù)
mysql
本項(xiàng)目使用mysql 作為持久化層
本項(xiàng)目采用了 mysql 的示例 employees 數(shù)據(jù)庫(kù), 需要的朋友可以自行下載 。
http://www3.ntu.edu.sg/home/ehchua/programming/sql/SampleDatabases.html
orm
dapper 短小精悍,被稱為orm中的瑞士軍刀。作者之前使用EF 比較多,總感覺(jué) EF 對(duì)一些復(fù)雜查詢需要原生sql支持的不是那么好,EF 生成sql 不好控制,涉及對(duì)性能要求比較高的地方,優(yōu)化起來(lái)不夠理想。作者在最近的幾個(gè)項(xiàng)目中接觸到dapper,它對(duì)原生sql查詢支持的相當(dāng)給力,使用起來(lái)也比較簡(jiǎn)便,感覺(jué)真是愛(ài)不釋手,嘿嘿。。。
https://github.com/StackExchange/Dapper架構(gòu)
服務(wù)端整體架構(gòu)采用倉(cāng)儲(chǔ)模式
Repository是一個(gè)獨(dú)立的層,介于領(lǐng)域?qū)优c數(shù)據(jù)映射層(數(shù)據(jù)訪問(wèn)層)之間。它的存在讓領(lǐng)域?qū)痈杏X(jué)不到數(shù)據(jù)訪問(wèn)層的存在,它提供一個(gè)類(lèi)似集合的接口提供給領(lǐng)域?qū)舆M(jìn)行領(lǐng)域?qū)ο蟮脑L問(wèn)。Repository是倉(cāng)庫(kù)管理員,領(lǐng)域?qū)有枰裁礀|西只需告訴倉(cāng)庫(kù)管理員,由倉(cāng)庫(kù)管理員把東西拿給它,并不需要知道東西實(shí)際放在哪。
此處照搬了dudu同學(xué)對(duì)倉(cāng)儲(chǔ)模式的理解。
倉(cāng)儲(chǔ)模式的好處:領(lǐng)域依賴接口與DB進(jìn)行交互,解除了二者之間的耦合,如果更換orm,DB層,采用這種模式,更換的代價(jià)最低。
前端技術(shù)
整體上SPA 結(jié)構(gòu)
Vue:
漸進(jìn)式 JavaScript 框架.
三大特點(diǎn):易用,靈活, 高效。
詳細(xì)信息見(jiàn)?https://cn.vuejs.org/VueRouter
vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,適合用于構(gòu)建單頁(yè)面應(yīng)用。vue的單頁(yè)面應(yīng)用是基于路由和組件的,路由用于設(shè)定訪問(wèn)路徑,并將路徑和組件映射起來(lái)。傳統(tǒng)的頁(yè)面應(yīng)用,是用一些超鏈接來(lái)實(shí)現(xiàn)頁(yè)面切換和跳轉(zhuǎn)的。在vue-router單頁(yè)面應(yīng)用中,則是路徑之間的切換,也就是組件的切換。
axios
axios 開(kāi)始崛起, 是一個(gè)基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端。
ElementUI
網(wǎng)站快速成型工具
Element,一套為開(kāi)發(fā)者、設(shè)計(jì)師和產(chǎn)品經(jīng)理準(zhǔn)備的基于 Vue 2.0 的桌面端組件庫(kù)
詳細(xì)信息見(jiàn)?http://element-cn.eleme.io/#/zh-CN
服務(wù)端項(xiàng)目結(jié)構(gòu)
服務(wù)端代碼地址:https://github.com/hbb0b0/Hbb0b0.CMS/tree/master/Hbb0b0.CMS.WebAPI
摘取部分類(lèi)予以說(shuō)明。
CMS.Common
通用工具的封裝
配置工具類(lèi)
DB配置
Cors配置
WebApi配置
DB工具類(lèi)
DapperContext
IRespository
ResponsitoryBase
包含獲取列表,獲取分頁(yè)列表,增刪改的通用操作的封裝
SimpleCRUD
github上對(duì)Dapper的進(jìn)一步分裝
消息
數(shù)據(jù)轉(zhuǎn)換
entity --> Dto
DTObase
PageList
CMS.DTO
返回給前端的數(shù)據(jù)對(duì)象,隔離DB model變化直接映射前端對(duì)象,使View與Model解耦。
CMS.Model
DB 中的表映射到 Model
CMS.IResponsity
DB 操作接口
CMS.Responsity
DB 操作接口的實(shí)現(xiàn)
CMS.IService
Serive接口,可以供給第三方調(diào)用,也是第三方調(diào)用的規(guī)范,同時(shí)也約束著服務(wù)實(shí)現(xiàn)。
目前提供給API層調(diào)用。
CMS.Service
Serive接口的實(shí)現(xiàn)
CMS.API
以WebAPI 形式提供給前臺(tái)調(diào)用,并不是嚴(yán)格按照 WebApi 規(guī)范 post,get,put,delete 調(diào)用.使用了 core中的 mvc 方式。
CMS.API 調(diào)用 IService 接口
CMS.Service 調(diào)用 IResponsitory接口
各接口與實(shí)現(xiàn)之間通過(guò)Core中的構(gòu)造函數(shù)注入方式聯(lián)接
服務(wù)端代碼說(shuō)明:
配置
{
? "Logging": {
? ? "IncludeScopes": false,
? ? "Debug": {
? ? ? "LogLevel": {
? ? ? ? "Default": "Information"
? ? ? }
? ? },
? ? "Console": {
? ? ? "LogLevel": {
? ? ? ? "Default": "Information"
? ? ? }
? ? }
? },
? "WebAPI": {
? ? "DB": {
? ? ? "ConnectionString": "server=localhost;database=employees;uid=root;pwd=sqlsa;charset='utf8';persistsecurityinfo=True;SslMode=none;Allow User Variables=True;",
? ? ? "ReadingConnectionString": "server=localhost;database=employees;uid=root;pwd=sqlsa;charset='utf8';persistsecurityinfo=True;SslMode=none;Allow User Variables=True;",
? ? ? "WritingConnectionString": "server=localhost;database=employees;uid=root;pwd=sqlsa;charset='utf8';persistsecurityinfo=True;SslMode=none;Allow User Variables=True;"
? ? },
? ? "Cors": {
? ? ? "Name": "CMSCorsConfig",
? ? ? "Original": "http://localhost:8080"
? ? }
? }
}
APIStartup
配置讀取與接口實(shí)現(xiàn)配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CMS.Common;
using CMS.Common.Config;
using CMS.Common.DB;
using CMS.IRepository;
using CMS.IService;
using CMS.Repository;
using CMS.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace CMS.WebApi
{
? ? public class Startup
? ? {
? ? ? ? public Startup(IConfiguration configuration)
? ? ? ? {
? ? ? ? ? ? Configuration = configuration;
? ? ? ? }
? ? ? ? public IConfiguration Configuration { get; }
? ? ? ? // This method gets called by the runtime. Use this method to add services to the container.
? ? ? ? public void ConfigureServices(IServiceCollection services)
? ? ? ? {
? ? ? ? ? ? services.AddMvc()
? ? ? ? ? ? //序列化設(shè)置
? ? ? ? ? ? .AddJsonOptions(options =>
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?//忽略循環(huán)引用
? ? ? ? ? ? ? ? ?options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
? ? ? ? ? ? ? ? ?//不使用駝峰樣式的key
? ? ? ? ? ? ? ? ?//options.SerializerSettings.ContractResolver = new DefaultContractResolver();
? ? ? ? ? ? ? ? ?//設(shè)置時(shí)間格式
? ? ? ? ? ? ? ? ?options.SerializerSettings.DateFormatString = "yyyy-MM-dd hh:mm:ss";?
? ? ? ? ? ? ?}
? ? ? ? );
? ? ? ? ? ? services.AddOptions();
? ? ? ? ? ? //讀取配置
? ? ? ? ? ? services.Configure<WebApiOption>(Configuration.GetSection("WebAPI"));
? ? ? ? ? ? IServiceProvider serviceProvider = services.BuildServiceProvider();
? ? ? ? ? ? //獲取配置
? ? ? ? ? ? WebApiOption config = serviceProvider.GetService<IOptions<WebApiOption>>().Value;
? ? ? ? ? ? //Cors配置
? ? ? ? ? ? AddCorsService(services,config);
? ? ? ? ? ? //DB Service
? ? ? ? ? ? AddDBService(services,config);
? ? ? ??
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// AddDBService
? ? ? ? /// </summary>
? ? ? ? /// <param name="services"></param>
? ? ? ? /// <param name="config"></param>
? ? ? ? private void AddDBService(IServiceCollection services,WebApiOption config)
? ? ? ? {
? ? ? ? ? ?
? ? ? ? ? ? //設(shè)置全局配置
? ? ? ? ? ? services.AddSingleton<IDapperContext>(_ => new DapperContext(
? ? ? ? ? ? ? ?config
? ? ? ? ? ? ? ?));
? ? ? ? ? ? services.AddScoped<IDepartmentRep, DepartmentRep>();
? ? ? ? ? ? services.AddScoped<IDepartmentService, DepartmentService>();
? ? ? ? ? ? services.AddScoped<IEmployeeRep, EmployeeRep>();
? ? ? ? ? ? services.AddScoped<IEmployeeService, EmployeeService>();
? ? ? ? ? ? services.AddScoped<ITitleRep, TitleRep>();
? ? ? ? ? ? services.AddScoped<ISalaryRep, SalaryRep>();
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// AddCorsService
? ? ? ? /// </summary>
? ? ? ? /// <param name="services"></param>
? ? ? ? /// <param name="config"></param>
? ? ? ? private void AddCorsService(IServiceCollection services, WebApiOption config)
? ? ? ? {
? ? ? ? ??
? ? ? ? ? ? //添加cors 服務(wù)
? ? ? ? ? ? services.AddCors(options =>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?options.AddPolicy(WebApiOption.CORS_POLICY_NAME, p => p.WithOrigins(config.Cors.Original)
? ? ? ? ? ? ?.AllowAnyMethod().AllowAnyHeader()));
? ? ? ? }
? ? ? ? // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
? ? ? ? public void Configure(IApplicationBuilder app, IHostingEnvironment env)
? ? ? ? {
? ? ? ? ? ? if (env.IsDevelopment())
? ? ? ? ? ? {
? ? ? ? ? ? ? ? app.UseDeveloperExceptionPage();
? ? ? ? ? ? }
? ? ? ? ? ? app.UseMvc();
? ? ? ? ? ? app.UseMvc(routes =>
? ? ? ? ? ? {
? ? ? ? ? ? ? ? routes.MapRoute(
? ? ? ? ? ? ? ? ? ? name: "default",
? ? ? ? ? ? ? ? ? ? template: "{controller}/{action}/{no?}",
? ? ? ? ? ? ? ? ? ? defaults: new { controller = "Home", action = "Index" });
? ? ? ? ? ? });
? ? ? ? ? ?
? ? ? ? ? ? //配置Cors
? ? ? ? ? ? app.UseCors(WebApiOption.CORS_POLICY_NAME);
? ? ? ? }
? ? }
}
ControllerBase
using CMS.Common.Config;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CMS.WebApi.Common
{
? ? [Route("api/[controller]")]
? ? [EnableCors(WebApiOption.CORS_POLICY_NAME)]
? ? public abstract class BaseController: Controller
? ? {
? ? ? ? protected readonly ILogger m_Logger;
? ? ? ? public BaseController(ILogger<BaseController> logger)
? ? ? ? {
? ? ? ? ? ? m_Logger = logger;
? ? ? ? }
? ? }
}
EmployeeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CMS.Common;
using CMS.Common.Config;
using CMS.Common.Message;
using CMS.DTO;
using CMS.Entity;
using CMS.IService;
using CMS.WebApi.Common;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace CMS.WebApi.Controllers
{
? ? public class EmployeeController : BaseController
? ? {
? ? ? ? private DBOption m_CmsOptions;
? ? ? ? private IEmployeeService m_Service;
? ? ? ? public EmployeeController(IOptions<DBOption> option, IEmployeeService employeeService, ILogger<EmployeeController> logger) : base(logger)
? ? ? ? {
? ? ? ? ? ? this.m_CmsOptions = option.Value;
? ? ? ? ? ? m_Service = employeeService;
? ? ? ? }
? ? ? ? [Route("[action]/{pageNumber}/{rowsPerPage}")]
? ? ? ? [HttpGet]
? ? ? ? public ReponseMessage<PagedList<EmployeeDTO>> GetPagedList(int pageNumber, int rowsPerPage)
? ? ? ? {
? ? ? ? ? ? var result = m_Service.GetPagedList(pageNumber, rowsPerPage);
? ? ? ? ? ? return m_Service.GetPagedList(pageNumber, rowsPerPage);
? ? ? ? }
? ? ? ? [Route("[action]")]
? ? ? ? [HttpPost]
? ? ? ? public ReponseMessage<PagedList<EmployeeDTO>> Query([FromBody]QueryCondition<EmployeeQuery> condition)
? ? ? ? {
? ? ? ? ? ? var result = m_Service.Query(condition);
? ? ? ? ? ? m_Logger.LogInformation("GetPagedList:{0}", JsonConvert.SerializeObject(result));
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? [Route("[action]/{no}")]
? ? ? ? [HttpGet]
? ? ? ? public ReponseMessage<EmployeeDetailDto> GetDetail(string no)
? ? ? ? {
? ? ? ? ? ? var result = m_Service.GetDetail(no);
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? [Route("[action]")]
? ? ? ? [HttpPost]
? ? ? ? public ReponseMessage<int> Add([FromBody]EmployeeDTO dto)
? ? ? ? {
? ? ? ? ? ? var result = m_Service.Add(dto);
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? [Route("[action]/{empNo}")]
? ? ? ? [HttpPost]
? ? ? ? public ReponseMessage<int> Delete(int empNo)
? ? ? ? {
? ? ? ? ? ? var result = m_Service.Delete(empNo);
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? [Route("[action]/")]
? ? ? ? [HttpPost]
? ? ? ? public ReponseMessage<int> Update([FromBody]EmployeeDTO dto)
? ? ? ? {
? ? ? ? ? ? var result = m_Service.Update(dto);
? ? ? ? ? ? return result;
? ? ? ? }
? ? }
}
IService
using CMS.Common;
using CMS.Common.Message;
using CMS.DTO;
using CMS.Entity;
using CMS.Model;
using System;
using System.Collections.Generic;
namespace CMS.IService
{
? ? public interface IEmployeeService
? ? {
? ? ? ? ReponseMessage<PagedList<EmployeeDTO>> GetPagedList(int pageNumber, int rowsPerPage);
? ? ? ? ReponseMessage<PagedList<EmployeeDTO>> Query(QueryCondition<EmployeeQuery> condition);
? ? ? ? ReponseMessage<EmployeeDetailDto> GetDetail(string emp_no);
? ? ? ? ReponseMessage<int> Add(EmployeeDTO dto);
? ? ? ? ReponseMessage<int> Update(EmployeeDTO dto);
? ? ? ? ReponseMessage<int> Delete(int emp_No);
? ? }
}
Service 實(shí)現(xiàn)
using CMS.Common;
using CMS.Common.Message;
using CMS.DTO;
using CMS.Entity;
using CMS.IRepository;
using CMS.IService;
using CMS.Model;
using CMS.Utility;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CMS.Service
{
? ? public class EmployeeService : IEmployeeService
? ? {
? ? ? ? private IEmployeeRep m_Rep;
? ? ? ? private ITitleRep m_TitleRep;
? ? ? ? private ISalaryRep m_SalaryRep;
? ? ? ? public EmployeeService(IEmployeeRep rep,ITitleRep titleRep, ISalaryRep salaryRep)
? ? ? ? {
? ? ? ? ? ? m_Rep = rep;
? ? ? ? ? ? m_TitleRep = titleRep;
? ? ? ? ? ? m_SalaryRep = salaryRep;
? ? ? ? }
? ? ??
? ? ? ? public ReponseMessage<EmployeeDetailDto> GetDetail(string emp_no)
? ? ? ? {
? ? ? ? ? ? ReponseMessage<EmployeeDetailDto> result = new ReponseMessage<EmployeeDetailDto>();
? ? ? ? ? ? EmployeeDetailDto data = new EmployeeDetailDto();
? ? ? ? ? ? var emp = m_Rep.Get(emp_no);
? ? ? ? ? ? data.Info = emp.JTransformTo<EmployeeDTO>();
? ? ? ? ? ? var titleList = m_TitleRep.GetList(string.Format($"where emp_no = {emp_no}"));
? ? ? ? ? ? var salaryList = m_SalaryRep.GetList(string.Format($"where emp_no = {emp_no} order by from_date "));
? ? ? ? ? ? result.Data = data;
? ? ? ? ? ? result.IsSuccess = true;
? ? ? ? ? ? if (titleList != null)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? result.Data.TitleList = titleList.JTransformTo<TitleDto>();
? ? ? ? ? ? }
? ? ? ? ? ? if (salaryList!=null)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? result.Data.SalaryList = salaryList.JTransformTo<SalaryDto>();
? ? ? ? ? ? }
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? public ReponseMessage<PagedList<EmployeeDTO>> GetPagedList(int pageNumber, int rowsPerPage)
? ? ? ? {
? ? ? ? ? ? int total = 0;
? ? ? ? ? ? ReponseMessage<PagedList<EmployeeDTO>> result = new ReponseMessage<PagedList<EmployeeDTO>>();
? ? ? ? ? ? result.Data = new PagedList<EmployeeDTO>();
? ? ? ? ? ? var modelResult= m_Rep.GetPagedList(pageNumber, rowsPerPage, null, null, out total);
? ? ? ? ? ? result.Data.TotalCount = total;
? ? ? ? ? ? result.Data.Items=modelResult.Items.JTransformTo<EmployeeDTO>();
? ? ? ? ? ? result.IsSuccess = true;
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? public ReponseMessage<PagedList<EmployeeDTO>> Query(QueryCondition<EmployeeQuery> condition)
? ? ? ? {
? ? ? ? ? ? ReponseMessage<PagedList<EmployeeDTO>> result = new ReponseMessage<PagedList<EmployeeDTO>>();
? ? ? ? ? ? result.Data = new PagedList<EmployeeDTO>();
? ? ? ? ? ? var modelResult = m_Rep.Query(condition);
? ? ? ? ? ? result.Data.TotalCount = modelResult.TotalCount;
? ? ? ? ? ? if (modelResult.TotalCount > 0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? result.Data.Items = modelResult.TotalCount>0 ? modelResult.Items.JTransformTo<EmployeeDTO>():new List<EmployeeDTO>();
? ? ? ? ? ? }
? ? ? ? ? ? result.IsSuccess = true;
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? public ReponseMessage<int> Add(EmployeeDTO dto)
? ? ? ? {
? ? ? ? ? ? ReponseMessage<int> result = new ReponseMessage<int>();
? ? ? ? ? ? if (dto==null )
? ? ? ? ? ? {
? ? ? ? ? ? ? ? result.IsSuccess = false;
? ? ? ? ? ? ? ? result.MessageInfo = new MessageInfo() { ErrorCode = -1, Message ="無(wú)效的參數(shù)" };
? ? ? ? ? ? }
? ? ? ? ? ? EmployeeModel entitity = dto.JTransformTo<EmployeeModel>();
? ? ? ? ? ? int? opResult =? m_Rep.CustomerAdd(entitity);
? ? ? ? ? ? if(opResult.HasValue && opResult>0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? result.IsSuccess = true;
? ? ? ? ? ? ? ? result.Data = opResult.Value;
? ? ? ? ? ? }
? ? ? ? ? ??
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? public ReponseMessage<int> Update(EmployeeDTO dto)
? ? ? ? {
? ? ? ? ? ? ReponseMessage<int> result = new ReponseMessage<int>();
? ? ? ? ? ? if (dto == null)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? result.IsSuccess = false;
? ? ? ? ? ? ? ? result.MessageInfo = new MessageInfo() { ErrorCode = -1, Message = "無(wú)效的參數(shù)" };
? ? ? ? ? ? }
? ? ? ? ? ? EmployeeModel entitity = dto.JTransformTo<EmployeeModel>();
? ? ? ? ? ? int? opResult = m_Rep.Update(entitity);
? ? ? ? ? ? if (opResult.HasValue && opResult > 0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? result.IsSuccess = true;
? ? ? ? ? ? ? ? result.Data = opResult.Value;
? ? ? ? ? ? }
? ? ? ? ? ? return result;
? ? ? ? }
? ? ? ? public ReponseMessage<int> Delete(int empNo)
? ? ? ? {
? ? ? ? ? ? ReponseMessage<int> result = new ReponseMessage<int>();
? ? ? ? ? ? int? opResult = m_Rep.Delete(empNo);
? ? ? ? ? ? if (opResult.HasValue && opResult ==1)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? result.IsSuccess = true;
? ? ? ? ? ? ? ? result.Data = opResult.Value;
? ? ? ? ? ? }
? ? ? ? ? ? return result;
? ? ? ? }
? ? }
}
IResponsitory
using CMS.Common;
using CMS.Common.DB;
using CMS.DTO;
using CMS.Entity;
using CMS.Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace CMS.IRepository
{
? ? public interface IEmployeeRep: IRepository<EmployeeModel>
? ? {
? ? ? ? PagedList<EmployeeDTO> Query(QueryCondition<EmployeeQuery> query);
? ? ? ? int? Add(EmployeeModel entity);
? ? ? ? int? CustomerAdd(EmployeeModel entity);
? ? ? ? int? Delete(int? empNo);
? ? ? ? int? Update(EmployeeModel entity);
? ? }
}
-Responsitory 實(shí)現(xiàn)
using CMS.Common;
using CMS.Common.DB;
using CMS.DTO;
using CMS.IRepository;
using CMS.Model;
using System;
using System.Collections.Generic;
using System.Text;
using Dapper;
namespace CMS.Repository
{
? public class EmployeeRep : ReponsitoryBase, IEmployeeRep
? {
? ? private static object m_sync_Object = new object();
? ? public EmployeeRep(IDapperContext dapper) : base(dapper)
? ?{
? ? }
? ? public int? Add(EmployeeModel entity)
? ? {
? ? ? ? return this.Insert(entity);
? ? }
? ? new public int? Update(EmployeeModel entity)
? ? {
? ? ? ? return base.Update(entity);
? ? }
? ? public int? CustomerAdd(EmployeeModel entity)
? ? {
? ? ? ? int cmdResult = -1;
? ? ? ? using (var connection = this.GetWritingConnection())
? ? ? ? {
? ? ? ? ? ? var sql = new StringBuilder(" set @maxNo=(select max(emp_no)+1 from employees) ;");
? ? ? ? ? ? sql.AppendLine("insert into employees(emp_no,first_name,last_name,gender,birth_date,hire_date) values(@maxNo,@first_name,@last_name,@gender,@birth_date,@hire_date); ");
? ? ? ? ? ? sql.AppendLine("select @maxNo;");
? ? ? ? ? ? cmdResult = connection.ExecuteScalar<int>(sql.ToString(), entity);
? ? ? ? }
? ? ? ? return cmdResult;
? ? }
? ? public int? Delete(int empNo)
? ? {
? ? ? ? int cmdResult = -1;
? ? ? ? using (var connection = this.GetWritingConnection())
? ? ? ? {
? ? ? ? ? ? cmdResult = connection.Execute("delete from employees where emp_no = @emp_no ;", new { emp_no = empNo });
? ? ? ? }
? ? ? ? return cmdResult;
? ? }
? ? public PagedList<EmployeeDTO> Query(QueryCondition<EmployeeQuery> query)
? ? {
? ? ? ? PagedList<EmployeeDTO> pagedList = new PagedList<EmployeeDTO>();
? ? ? ? #region sql
? ? ? ? var sql = new StringBuilder("SELECT SQL_CALC_FOUND_ROWS * from employees ");
? ? ? ? #endregion
? ? ? ? sql.AppendLine(" Where 1=1");
? ? ? ? if (!string.IsNullOrEmpty(query.Param.First_Name))
? ? ? ? {
? ? ? ? ? ? sql.AppendLine(string.Format(" and First_Name like '{0}'", query.GetLikeValue(query.Param.First_Name)));
? ? ? ? }
? ? ? ? if (!string.IsNullOrEmpty(query.Param.Last_Name))
? ? ? ? {
? ? ? ? ? ? sql.AppendLine(string.Format(" and last_Name like '{0}'", query.GetLikeValue(query.Param.Last_Name)));
? ? ? ? }
? ? ? ? if (!string.IsNullOrEmpty(query.Param.Emp_No))
? ? ? ? {
? ? ? ? ? ? sql.AppendLine(string.Format(" and emp_no = @Emp_No"));
? ? ? ? }
? ? ? ? if (!string.IsNullOrEmpty(query.Param.Gender))
? ? ? ? {
? ? ? ? ? ? sql.AppendLine(string.Format(" and gender = @Gender"));
? ? ? ? }
? ? ? ? DateTime? hire_date_start = null;
? ? ? ? DateTime? hire_date_end = null;
? ? ? ? if (query.Param.Hire_Date_Range != null)
? ? ? ? {
? ? ? ? ? ? if (query.Param.Hire_Date_Range[0].HasValue)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? hire_date_start = query.Param.Hire_Date_Range[0];
? ? ? ? ? ? ? ? sql.AppendLine(string.Format(" and hire_date >= @Hire_Date_Range_Start"));
? ? ? ? ? ? }
? ? ? ? ? ? if (query.Param.Hire_Date_Range[1].HasValue)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? hire_date_end = query.Param.Hire_Date_Range[1];
? ? ? ? ? ? ? ? sql.AppendLine(string.Format(" and hire_date <= @Hire_Date_Range_End"));
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? DateTime? birth_date_start = null;
? ? ? ? DateTime? birth_date_end = null;
? ? ? ? if (query.Param.Birth_Date_Range != null)
? ? ? ? {
? ? ? ? ? ? if (query.Param.Birth_Date_Range[0].HasValue)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? birth_date_start = query.Param.Birth_Date_Range[0];
? ? ? ? ? ? ? ? sql.AppendLine(string.Format(" and birth_date >= @Birth_Date_Range_Start"));
? ? ? ? ? ? }
? ? ? ? ? ? if (query.Param.Birth_Date_Range[1].HasValue)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? birth_date_end = query.Param.Birth_Date_Range[1];
? ? ? ? ? ? ? ? sql.AppendLine(string.Format(" and birth_date <= @Birth_Date_Range_End"));
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? sql.AppendLine(" order by emp_no desc");
? ? ? ? sql.AppendLine($" LIMIT {(query.pageInfo.PageIndex - 1) * query.pageInfo.PageSize},{query.pageInfo.PageSize}");
? ? ? ? sql.Append(";");
? ? ? ? using (var connection = this.GetReadingConnection())
? ? ? ? {
? ? ? ? ? ? var result = connection.Query<EmployeeDTO>(sql.ToString(),
? ? ? ? ? ? ? ? new
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? Emp_No = query.Param.Emp_No,
? ? ? ? ? ? ? ? ? ? Hire_Date_Range_Start = hire_date_start,
? ? ? ? ? ? ? ? ? ? Hire_Date_Range_End = hire_date_end,
? ? ? ? ? ? ? ? ? ? Birth_Date_Range_Start = birth_date_start,
? ? ? ? ? ? ? ? ? ? Birth_Date_Range_End = birth_date_end,
? ? ? ? ? ? ? ? ? ? Gender = query.Param.Gender
? ? ? ? ? ? ? ? }).AsList();
? ? ? ? ? ? pagedList.Items = result;
? ? ? ? ? ? pagedList.TotalCount = connection.ExecuteScalar<int>("SELECT FOUND_ROWS();");
? ? ? ? }
? ? ? ? return pagedList;
? ? }
}
目前測(cè)試 empoyee 30萬(wàn)條分頁(yè)數(shù)據(jù)大致在400ms左右
相關(guān)文章:
淺談開(kāi)發(fā)模式及架構(gòu)發(fā)展
dotnet core webapi +vue 搭建前后端完全分離web架構(gòu)(一)
原文地址:http://www.cnblogs.com/hbb0b0/p/8391598.html
.NET社區(qū)新聞,深度好文,歡迎訪問(wèn)公眾號(hào)文章匯總 http://www.csharpkit.com
總結(jié)
以上是生活随笔為你收集整理的dotnetcore+vue+elementUI 前后端分离架 二(后端篇)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: .NET 文档数据库 RavenDB 4
- 下一篇: dotnetcore+vue+eleme