首页 > 其他分享 >房产中介管理软件第5课:框架整体分层

房产中介管理软件第5课:框架整体分层

时间:2022-09-21 14:59:35浏览次数:69  
标签:System 返回 分层 中介 response 管理软件 new using public

整体架构设计如下

 

1、Model层:所有实体类

2、Common层:数据库访问、配置文件读取、帮助类、实用工具类等

3、Repository层:仓储层,用于数据库访问,尽量不做逻辑判断

4、Service层:服务层,逻辑判断,上接API层,下接Repository层

5、API层:对外提供的接口

一、Model实体层

1、BaseEntity.cs新建了几个通用字段,其他实体类可以基于此类做新增

using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Model
{
    public class BaseEntity
    {
        #region 通用属性
        /// <summary>
        /// 是否删除
        /// </summary>
        [Required]
        public bool IsDeleted { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        [Required]
        public DateTime CreateTime { get; set; }

        /// <summary>
        /// 编辑时间
        /// </summary>
        [Required]
        public DateTime ModifyTime { get; set; }

        /// <summary>
        /// 版本编号
        /// </summary>
        [Required]
        [SqlSugar.SugarColumn(IsEnableUpdateVersionValidation = true)]
        public Guid Version { get; set; }

        #endregion

        #region 通用方法 

        /// <summary>
        /// 转化为json
        /// </summary>
        /// <returns>json字符串</returns>
        public String ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }

        /// <summary>
        /// 创建赋值
        /// </summary>
        public void AssignmentCreateValue()
        {
            this.IsDeleted = false;
            this.CreateTime = DateTime.Now;
            this.ModifyTime = this.CreateTime;
            this.Version = Guid.NewGuid();
        }

        /// <summary>
        /// 编辑赋值
        /// </summary>
        public void AssignmentModifyValue()
        {
            this.ModifyTime = DateTime.Now;
            this.Version = Guid.NewGuid();
        }

        /// <summary>
        /// 逻辑删除赋值
        /// </summary>
        public void AssignmentDeleteValue()
        {
            this.IsDeleted = true;
            this.ModifyTime = DateTime.Now;
            this.Version = Guid.NewGuid();
        }
        #endregion
    }
}

2、新建了两个数据返回类,ResponseObject用于返回object类型的数据(bool,int,long等),ResponseEntity用于返回实体类型的数据(可以是单个实体,也可以是list)

ResponseBase.cs(Service层使用)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Model
{
    /// <summary>
    /// 最终操作结果
    /// </summary>
    public enum OperationResult
    {
        Success,
        Failed
    }


    public class ResponseBase
    {
        /// <summary>
        /// 操作结果
        /// </summary>
        public OperationResult OperationResult { get; set; }

        /// <summary>
        /// 操作描述
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 跟踪ID
        /// </summary>
        public int TraceID { get; set; }
    }
    
}

ResponseObject.cs(Service层使用)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Model
{
    public class ResponseObject<T> : ResponseBase
    {
        /// <summary>
        /// 返回结果
        /// </summary>
        public T Result { get; set; }
    }

}

ResponseEntity.cs(Service层使用)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Model
{
    public class ResponseEntity<T>: ResponseBase where T : class, new()
    {
        private IList<T> _list;
        private T _entity;

        public ResponseEntity()
        {
            _list = new List<T>();
            _entity = new T();
        }

        /// <summary>
        /// 返回列表
        /// </summary>
        public IList<T> EntityList
        {
            get { return _list; }
            set { _list = value; }
        }

        /// <summary>
        /// 返回实体
        /// </summary>
        public T Entity
        {
            get { return _entity; }
            set { _entity = value; }
        }

        /// <summary>
        /// 分页参数
        /// </summary>
        public PagingParameters PagingParameters { get; set; }

        /// <summary>
        /// 数据总数
        /// </summary>
        public long TotalCount { get; set; }
    }

    /// <summary>
    /// 分页参数
    /// </summary>
    public class PagingParameters
    {
        public int PageIndex { set; get; }
        public int PageSize { set; get; }
        public long TotalCount { set; get; }
    }
}

3、另外,ApiResult.cs是用于返回数据(API层使用)

ApiConstant.cs

namespace Randy.Fang.Model
{
    /// <summary>
    /// 常用类
    /// </summary>
    public class ApiConstant
    {
        /// <summary>
        /// 提示代码
        /// </summary>
        public const int INFO_CODE = 4001;

        /// <summary>
        /// 未登录代码
        /// </summary>
        public const int NO_LOGIN_CODE = 1001;

        /// <summary>
        /// 未登录代码
        /// </summary>
        public const string NO_LOGIN_TEXT = "您已经登录会话过期,需要重新登录";

        /// <summary>
        /// 成功代码
        /// </summary>
        public const int SUCCESS_CODE = 0;

        /// <summary>
        /// 成功消息
        /// </summary>
        public const string SUCCESS_TEXT = "成功";

        /// <summary>
        /// 查询错误
        /// </summary>
        public const int QUERY_ERROR_CODE = 5001;

        /// <summary>
        /// 查询错误
        /// </summary>
        public const string QUERY_ERROR_TEXT = "查询错误";

        /// <summary>
        /// 保存错误
        /// </summary>
        public const int SAVE_ERROR_CODE = 5002;

        /// <summary>
        /// 保存错误
        /// </summary>
        public const string SAVE_ERROR_TEXT = "保存错误";

        /// <summary>
        /// 删除错误
        /// </summary>
        public const int DELETE_ERROR_CODE = 5003;

        /// <summary>
        /// 删除错误
        /// </summary>
        public const string DELETE_ERROR_TEXT = "删除错误";
    }
}

ApiResult.cs

namespace Randy.Fang.Model
{
    /// <summary>
    ///  描述: API返回结果
    /// </summary>
    public class ApiResult
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public ApiResult()
        {
            this.code = ApiConstant.SUCCESS_CODE;
            this.msg = "成功";
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="data"></param>
        public ApiResult(object data)
        {
            this.data = data;
            this.code = ApiConstant.SUCCESS_CODE;
            this.msg = "成功";
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="intCode"></param>
        /// <param name="strMsg"></param>
        public ApiResult(int intCode, string strMsg)
        {
            this.code = intCode;
            this.msg = strMsg;
        }

        /// <summary>
        /// 返回代码
        /// </summary>
        public int code { set; get; }

        /// <summary>
        /// 返回内容
        /// </summary>
        public string msg { set; get; }

        /// <summary>
        /// 数据对象
        /// </summary>          
        public object data { get; set; }

        /// <summary>
        /// 记录总数
        /// </summary>
        public long count { get; set; }
    }
}

二、Common层

这层最主要的就是数据库访问类了,使用的是SqlSugar的单例模式

DBContext.cs

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Common
{
    /// <summary>
    /// 数据库服务类
    /// </summary>
    public class DBContext
    {
        /// <summary>
        /// 单例模式
        /// </summary>
        public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig(){
            DbType = (DbType)GlobalContext.DBConfig.DBType,
            InitKeyType = InitKeyType.Attribute,
            IsAutoCloseConnection = true,
            ConnectionString = GlobalContext.DBConfig.ConnectionString,//主库
            MoreSettings = new ConnMoreSettings()
            {
                //MySql禁用NVarchar
                DisableNvarchar = (DbType)GlobalContext.DBConfig.DBType == DbType.MySql ? true : false
            }
        },
        db => {

            //单例参数配置,所有上下文生效
            db.Ado.CommandTimeOut = GlobalContext.DBConfig.CommandTimeOut;//数据库超时时间,单位秒


            //每次Sql执行前事件
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                var queryString = new KeyValuePair<string, SugarParameter[]>(sql, pars);
                if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine($"==============新增/修改操作==============");
                }
                if (sql.StartsWith("DELETE"))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"==============删除操作==============");
                }
                if (sql.StartsWith("SELECT"))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"==============查询操作==============");
                }
                //ToSqlExplain 在标题6中有完整代码
                Console.WriteLine(ToSqlExplain.GetSql(queryString));//输出sql
                Console.ForegroundColor = ConsoleColor.White;
            };

            //SQL执行完
            db.Aop.OnLogExecuted = (sql, pars) =>
            {
                //执行完可以输出SQL执行时间
                Console.Write($"SQL:{sql},\r\nTimeSpan:{db.Ado.SqlExecutionTime.TotalMilliseconds}ms\r\n");
            };

            //SQL报错
            db.Aop.OnError = (exp) =>
            {
                //exp.sql 这样可以拿到错误SQL 
                Console.WriteLine(exp.Sql);
            };
        });
    }
}

配置读取可以见下一篇文章。

三、Repository仓储层

先建立两个基类,用于通用仓储层

IBaseRepository.cs

using Randy.Fang.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Repository
{
    /// <summary>
    /// 数据访问仓库接口
    /// </summary>
    /// <typeparam name="TEntity">实体类型</typeparam>
    public interface IBaseRepository<TEntity> where TEntity : class
    {
        /// <summary>
        /// 插入实体 忽略NULL
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        bool Insert(TEntity entity);

        /// <summary>
        /// 插入实体,返回自增列的值
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        int InsertReturnIdentity(TEntity entity);

        /// <summary>
        /// 插入实体,返回自增列的值
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        long InsertReturnBigIdentity(TEntity entity);

        /// <summary>
        /// 根据唯一主键删除
        /// </summary>
        /// <param name="keyValue">唯一主键</param>
        /// <returns>删除成功返回true</returns>
        bool Delete(object keyValue);

        /// <summary>
        /// 根据表达式删除
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>删除成功返回true</returns>
        bool Delete(Expression<Func<TEntity, bool>> expression);

        /// <summary>
        /// 将实体对象更新到数据库 忽略属性为NULL
        /// </summary>
        /// <param name="entity">必需包含主键并且不能为匿名对象</param>
        /// <returns>更新成功返回true</returns>
        bool Update(TEntity entity);

        /// <summary>
        /// 检测主键对应的数据是否存在
        /// </summary>
        /// <param name="ID">主键值</param>
        /// <returns>存在返回true,不存在返回false</returns>
        bool IsExist(int ID);

        /// <summary>
        /// 检测主键对应的数据是否存在
        /// </summary>
        /// <param name="ID">主键值</param>
        /// <returns>存在返回true,不存在返回false</returns>
        bool IsExist(string ID);

        /// <summary>
        /// 根据主键查询对象实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns>实体</returns>
        TEntity FindEntity(object keyValue);

        /// <summary>
        /// 根据条件查询第一条数据
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>实体</returns>
        TEntity FindFirst(Expression<Func<TEntity, bool>> expression);

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>实体集合</returns>
        List<TEntity> FindList(Expression<Func<TEntity, bool>> expression);

        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        List<TEntity> FindAllList();

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <returns>实体集合</returns>
        List<TEntity> GetList(string strsql);

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <param name="intTop">前几行</param>
        /// <param name="expression">表达式</param>
        /// <returns>实体集合</returns>
        List<TEntity> FindTopList(int intTop, Expression<Func<TEntity, bool>> expression);

        /// <summary>
        /// 获得记录数
        /// </summary>
        /// <param name="pageWhere">查询条件</param>
        /// <param name="tableName">查询的表名</param>
        /// <returns>返回ListModel</returns>
        int GetListCount(string pageWhere, string tableName);

        /// <summary>
        /// 获得分页数据
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageWhere">查询条件</param>
        /// <param name="pageOrder">排序</param>
        /// <param name="tableName">查询的表名</param>
        /// <returns>返回ListModel</returns>
        List<TEntity> GetListPageData(int pageSize, int pageIndex, string pageWhere, string pageOrder, string tableName);

        /// <summary>
        /// 获取满足表达式的记录条数
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns></returns>
        int FindCount(Expression<Func<TEntity, bool>> expression);
    }
}

BaseRepository.cs

using Randy.Fang.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Repository
{
    /// <summary>
    /// 仓储基类
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class BaseRepository<TEntity> : DBContext, IBaseRepository<TEntity> where TEntity : class, new()
    {
        /// <summary>
        /// 插入实体 忽略NULL
        /// 对于自增列的值赋值没有意义,赋值和不赋值运行效果一样
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        public virtual bool Insert(TEntity entity)
        {
            return Db.Insertable(entity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 插入实体,返回自增列的值
        /// 对于自增列的值赋值没有意义,赋值和不赋值运行效果一样
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        public virtual int InsertReturnIdentity(TEntity entity)
        {
            return Db.Insertable(entity).ExecuteReturnIdentity();
        }

        /// <summary>
        /// 插入实体,返回自增列的值
        /// 对于自增列的值赋值没有意义,赋值和不赋值运行效果一样
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        public virtual long InsertReturnBigIdentity(TEntity entity)
        {
            return Db.Insertable(entity).ExecuteReturnBigIdentity();
        }

        /// <summary>
        /// 根据唯一主键删除
        /// 主键不存在,为False 
        /// </summary>
        /// <param name="keyValue">唯一主键</param>
        /// <returns>删除成功返回true</returns>
        public virtual bool Delete(object keyValue)
        {
            return Db.Deleteable<TEntity>().In(keyValue).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 根据表达式删除
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>删除成功返回true</returns>
        public virtual bool Delete(Expression<Func<TEntity, bool>> expression)
        {
            return Db.Deleteable<TEntity>().Where(expression).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 将实体对象更新到数据库 忽略属性为NULL
        /// 主键在数据库里不存在则返回False
        /// 没有主键则返回False
        /// </summary>
        /// <param name="entity">必需包含主键并且不能为匿名对象</param>
        /// <returns>更新成功返回true</returns>
        public virtual bool Update(TEntity entity)
        {
            return Db.Updateable(entity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 检测主键对应的数据是否存在
        /// </summary>
        /// <param name="ID">主键值</param>
        /// <returns>存在返回true,不存在返回false</returns>
        public bool IsExist(int ID)
        {
            bool ReturnResult = false;

            List<TEntity> list = Db.Queryable<TEntity>().In(new int[] { ID }).ToList();
            if (list != null)
            {
                if (list.Count == 0)
                {
                    ReturnResult = false;
                }
                else
                {
                    ReturnResult = true;
                }
            }
            else
            {
                ReturnResult = false;
            }

            return ReturnResult;
        }

        /// <summary>
        /// 检测主键对应的数据是否存在
        /// </summary>
        /// <param name="ID">主键值</param>
        /// <returns>存在返回true,不存在返回false</returns>
        public bool IsExist(string ID)
        {
            bool ReturnResult = false;

            List<TEntity> list = Db.Queryable<TEntity>().In(new string[] { ID }).ToList();
            if (list != null)
            {
                if (list.Count == 0)
                {
                    ReturnResult = false;
                }
                else
                {
                    ReturnResult = true;
                }
            }
            else
            {
                ReturnResult = false;
            }

            return ReturnResult;
        }

        /// <summary>
        /// 根据主键查询对象实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns>实体</returns>
        public virtual TEntity FindEntity(object keyValue)
        {
            return Db.Queryable<TEntity>().InSingle(keyValue);
        }

        /// <summary>
        /// 根据条件查询第一条数据
        /// </summary>
        /// <returns>实体</returns>
        public virtual TEntity FindFirst(Expression<Func<TEntity, bool>> expression)
        {
            return Db.Queryable<TEntity>().Where(expression).First();
        }

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>实体集合</returns>
        public virtual List<TEntity> FindList(Expression<Func<TEntity, bool>> expression)
        {
            return Db.Queryable<TEntity>().Where(expression).ToList();
        }

        /// <summary>
        /// 查找所有List集合
        /// </summary>
        /// <returns>实体集合</returns>
        public virtual List<TEntity> FindAllList()
        {
            return Db.Queryable<TEntity>().ToList();
        }

        /// <summary>
        /// 查找符合条件的实体集合
        /// </summary>
        /// <param name="strsql">sql语句</param>
        /// <returns>实体集合</returns>
        public virtual List<TEntity> GetList(string strsql)
        {
            return Db.Queryable<TEntity>().Where(strsql).ToList();
        }

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <param name="intTop">前几行</param>
        /// <param name="expression">表达式</param>
        /// <returns>实体集合</returns>
        public virtual List<TEntity> FindTopList(int intTop, Expression<Func<TEntity, bool>> expression)
        {
            return Db.Queryable<TEntity>().Take(intTop).Where(expression).ToList();
        }

        #region 获得记录数
        /// <summary>
        /// 获得记录数
        /// 不是本表的也可以进行查询,但是建议只查本表的
        /// 
        /// </summary>
        /// <param name="pageWhere">查询条件</param>
        /// <param name="tableName">查询的表名 </param>
        /// <returns>返回ListModel</returns>
        public int GetListCount(string pageWhere, string tableName)
        {
            int ReturnVale = 0;

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from " + tableName);
            if (pageWhere.Trim() != "")
            {
                strSql.Append(" where " + pageWhere);
            }

            ReturnVale = Db.Ado.GetInt(DataAdapterHelper.CreateCountSQL(tableName, pageWhere));

            return ReturnVale;
        }
        #endregion

        /// <summary>
        /// 获得分页数据
        /// pageSize小于0返回空,等于0返回全部
        /// pageIndex小于1则返回第一页,大于最大页数返回最后一页
        /// pageWhere必填项,不可为"",可写为1=1
        /// pageOrder必填项,不可为"",可写为 1(等数字)或者 ID (可倒序排列 ID desc)
        /// tableName必填项,不可写其他表名
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageWhere">查询条件</param>
        /// <param name="pageOrder">排序</param>
        /// <param name="tableName">查询的表名</param>
        /// <returns>返回ListModel</returns>
        public List<TEntity> GetListPageData(int pageSize, int pageIndex, string pageWhere, string pageOrder, string tableName)
        {
            List<TEntity> ListData = new List<TEntity>();

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from " + tableName);
            if (pageWhere.Trim() != "")
            {
                strSql.Append(" where " + pageWhere);
            }

            int totalCount = 0;
            totalCount = Db.Ado.GetInt(DataAdapterHelper.CreateCountSQL(tableName, pageWhere));
            ListData = Db.Ado.SqlQuery<TEntity>(DataAdapterHelper.CreatePageSQL(totalCount, pageSize, pageIndex, strSql.ToString(), pageOrder, tableName));

            return ListData;
        }

        /// <summary>
        /// 获取满足表达式的记录条数
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns></returns>
        public int FindCount(Expression<Func<TEntity, bool>> expression)
        {
            return Db.Queryable<TEntity>().Count(expression);
        }
    }
}

四、Service服务层

先建立两个基类,用于通用方法

IBaseService.cs

using Randy.Fang.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Service
{
    /// <summary>
    /// 服务类接口
    /// </summary>
    /// <typeparam name="TEntity">实体类型</typeparam>
    public interface IBaseService<TEntity> where TEntity : class, new()
    {
        /// <summary>
        /// 插入实体 忽略NULL
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        ResponseObject<bool> Insert(TEntity entity);

        /// <summary>
        /// 插入实体,返回自增列的值
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        ResponseObject<int> InsertReturnIdentity(TEntity entity);

        /// <summary>
        /// 插入实体,返回自增列的值
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        ResponseObject<long> InsertReturnBigIdentity(TEntity entity);

        /// <summary>
        /// 根据唯一主键删除
        /// </summary>
        /// <param name="keyValue">唯一主键</param>
        /// <returns>删除成功返回true</returns>
        ResponseObject<bool> Delete(object keyValue);

        /// <summary>
        /// 根据表达式删除
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>删除成功返回true</returns>
        ResponseObject<bool> Delete(Expression<Func<TEntity, bool>> expression);

        /// <summary>
        /// 将实体对象更新到数据库 忽略属性为NULL
        /// </summary>
        /// <param name="entity">必需包含主键并且不能为匿名对象</param>
        /// <returns>更新成功返回true</returns>
        ResponseObject<bool> Update(TEntity entity);

        /// <summary>
        /// 检测主键对应的数据是否存在
        /// </summary>
        /// <param name="ID">主键值</param>
        /// <returns>存在返回true,不存在返回false</returns>
        ResponseObject<bool> IsExist(int ID);

        /// <summary>
        /// 检测主键对应的数据是否存在
        /// </summary>
        /// <param name="ID">主键值</param>
        /// <returns>存在返回true,不存在返回false</returns>
        ResponseObject<bool> IsExist(string ID);

        /// <summary>
        /// 根据主键查询对象实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns>实体</returns>
        ResponseEntity<TEntity> FindEntity(object keyValue);

        /// <summary>
        /// 根据条件查询第一条数据
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>实体</returns>
        ResponseEntity<TEntity> FindFirst(Expression<Func<TEntity, bool>> expression);

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>实体集合</returns>
        ResponseEntity<TEntity> FindList(Expression<Func<TEntity, bool>> expression);

        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        ResponseEntity<TEntity> FindAllList();

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <returns>实体集合</returns>
        ResponseEntity<TEntity> GetList(string strsql);

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <param name="intTop">前几行</param>
        /// <param name="expression">表达式</param>
        /// <returns>实体集合</returns>
        ResponseEntity<TEntity> FindTopList(int intTop, Expression<Func<TEntity, bool>> expression);

        /// <summary>
        /// 获得记录数
        /// </summary>
        /// <param name="pageWhere">查询条件</param>
        /// <param name="tableName">查询的表名</param>
        /// <returns>返回ListModel</returns>
        ResponseObject<int> GetListCount(string pageWhere, string tableName);

        /// <summary>
        /// 获得分页数据
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageWhere">查询条件</param>
        /// <param name="pageOrder">排序</param>
        /// <param name="tableName">查询的表名</param>
        /// <returns>返回ListModel</returns>
        ResponseEntity<TEntity> GetListPageData(int pageSize, int pageIndex, string pageWhere, string pageOrder, string tableName);

        /// <summary>
        /// 获取满足表达式的记录条数
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns></returns>
        ResponseObject<int> FindCount(Expression<Func<TEntity, bool>> expression);
    }
}

BaseService.cs

using Randy.Fang.Model;
using Randy.Fang.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Service
{
    /// <summary>
    /// 服务类
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class BaseService<TEntity> : IBaseService<TEntity> where TEntity : class, new()
    {
        //返回Repository
        protected IBaseRepository<TEntity> Repository { get; set; }

        /// <summary>
        /// 插入实体 忽略NULL
        /// 对于自增列的值赋值没有意义,赋值和不赋值运行效果一样
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        public ResponseObject<bool> Insert(TEntity entity)
        {
            var response = new ResponseObject<bool>();
            try
            {
                response.Result = Repository.Insert(entity);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 插入实体,返回自增列的值
        /// 对于自增列的值赋值没有意义,赋值和不赋值运行效果一样
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        public ResponseObject<int> InsertReturnIdentity(TEntity entity)
        {
            var response = new ResponseObject<int>();
            try
            {
                response.Result = Repository.InsertReturnIdentity(entity);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 插入实体,返回自增列的值
        /// 对于自增列的值赋值没有意义,赋值和不赋值运行效果一样
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>插入成功返回true</returns>
        public ResponseObject<long> InsertReturnBigIdentity(TEntity entity)
        {
            var response = new ResponseObject<long>();
            try
            {
                response.Result = Repository.InsertReturnBigIdentity(entity);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 根据唯一主键删除
        /// 主键不存在,为False 
        /// </summary>
        /// <param name="keyValue">唯一主键</param>
        /// <returns>删除成功返回true</returns>
        public ResponseObject<bool> Delete(object keyValue)
        {
            var response = new ResponseObject<bool>();
            try
            {
                response.Result = Repository.Delete(keyValue);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 根据表达式删除
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>删除成功返回true</returns>
        public ResponseObject<bool> Delete(Expression<Func<TEntity, bool>> expression)
        {
            var response = new ResponseObject<bool>();
            try
            {
                response.Result = Repository.Delete(expression);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 将实体对象更新到数据库 忽略属性为NULL
        /// 主键在数据库里不存在则返回False
        /// 没有主键则返回False
        /// </summary>
        /// <param name="entity">必需包含主键并且不能为匿名对象</param>
        /// <returns>更新成功返回true</returns>
        public ResponseObject<bool> Update(TEntity entity)
        {
            var response = new ResponseObject<bool>();
            try
            {
                response.Result = Repository.Update(entity);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 检测主键对应的数据是否存在
        /// </summary>
        /// <param name="ID">主键值</param>
        /// <returns>存在返回true,不存在返回false</returns>
        public ResponseObject<bool> IsExist(int ID)
        {
            var response = new ResponseObject<bool>();
            try
            {
                response.Result = Repository.IsExist(ID);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 检测主键对应的数据是否存在
        /// </summary>
        /// <param name="ID">主键值</param>
        /// <returns>存在返回true,不存在返回false</returns>
        public ResponseObject<bool> IsExist(string ID)
        {
            var response = new ResponseObject<bool>();
            try
            {
                response.Result = Repository.IsExist(ID);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 根据主键查询对象实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns>实体</returns>
        public ResponseEntity<TEntity> FindEntity(object keyValue)
        {
            var response = new ResponseEntity<TEntity>();
            try
            {
                response.Entity = Repository.FindEntity(keyValue);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 根据条件查询第一条数据
        /// </summary>
        /// <returns>实体</returns>
        public ResponseEntity<TEntity> FindFirst(Expression<Func<TEntity, bool>> expression)
        {
            var response = new ResponseEntity<TEntity>();
            try
            {
                response.Entity = Repository.FindFirst(expression);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>实体集合</returns>
        public ResponseEntity<TEntity> FindList(Expression<Func<TEntity, bool>> expression)
        {
            var response = new ResponseEntity<TEntity>();
            try
            {
                response.EntityList = Repository.FindList(expression);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 查找所有List集合
        /// </summary>
        /// <returns>实体集合</returns>
        public ResponseEntity<TEntity> FindAllList()
        {
            var response = new ResponseEntity<TEntity>();
            try
            {
                response.EntityList = Repository.FindAllList();
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 查找符合条件的实体集合
        /// </summary>
        /// <param name="strsql">sql语句</param>
        /// <returns>实体集合</returns>
        public ResponseEntity<TEntity> GetList(string strsql)
        {
            var response = new ResponseEntity<TEntity>();
            try
            {
                response.EntityList = Repository.GetList(strsql);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 查找符合表达式的List集合
        /// </summary>
        /// <param name="intTop">前几行</param>
        /// <param name="expression">表达式</param>
        /// <returns>实体集合</returns>
        public ResponseEntity<TEntity> FindTopList(int intTop, Expression<Func<TEntity, bool>> expression)
        {
            var response = new ResponseEntity<TEntity>();
            try
            {
                response.EntityList = Repository.FindTopList(intTop, expression);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        #region 获得记录数
        /// <summary>
        /// 获得记录数
        /// 不是本表的也可以进行查询,但是建议只查本表的
        /// 
        /// </summary>
        /// <param name="pageWhere">查询条件</param>
        /// <param name="tableName">查询的表名 </param>
        /// <returns>返回ListModel</returns>
        public ResponseObject<int> GetListCount(string pageWhere, string tableName)
        {
            var response = new ResponseObject<int>();
            try
            {
                response.Result = Repository.GetListCount(pageWhere, tableName);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }
        #endregion

        /// <summary>
        /// 获得分页数据
        /// pageSize小于0返回空,等于0返回全部
        /// pageIndex小于1则返回第一页,大于最大页数返回最后一页
        /// pageWhere必填项,不可为"",可写为1=1
        /// pageOrder必填项,不可为"",可写为 1(等数字)或者 ID (可倒序排列 ID desc)
        /// tableName必填项,不可写其他表名
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageWhere">查询条件</param>
        /// <param name="pageOrder">排序</param>
        /// <param name="tableName">查询的表名</param>
        /// <returns>返回ListModel</returns>
        public ResponseEntity<TEntity> GetListPageData(int pageSize, int pageIndex, string pageWhere, string pageOrder, string tableName)
        {
            var response = new ResponseEntity<TEntity>();
            try
            {
                response.EntityList = Repository.GetListPageData(pageSize, pageIndex, pageWhere, pageOrder, tableName);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }

        /// <summary>
        /// 获取满足表达式的记录条数
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns></returns>
        public ResponseObject<int> FindCount(Expression<Func<TEntity, bool>> expression)
        {
            var response = new ResponseObject<int>();
            try
            {
                response.Result = Repository.FindCount(expression);
            }
            catch (Exception ex)
            {
                response.OperationResult = OperationResult.Failed;
                response.Message = ex.Message;
                response.TraceID = new Random().Next(10000, 99999);
            }
            return response;
        }
    }
}

我们可以基于基类建立其他服务类文件,比如我建立一个TBAction.cs文件

using Randy.Fang.Model;
using Randy.Fang.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randy.Fang.Service
{
    /// <summary>
    /// TBActionService业务层实现
    /// </summary>
    public class TBActionService : BaseService<TBAction>
    {
        public TBActionService()
        {
            Repository = new BaseRepository<TBAction>();
        }
    }
}

五、API调用演示

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Randy.Fang.Model;
using Randy.Fang.Service;

namespace Randy.Fang.API.Controllers
{
    /// <summary>
    /// 系统登录控制器
    /// </summary>
    [Route("api/v8/[controller]")]
    [ApiController]
    [ApiGroup(ApiGroup.Auth)]
    public class IndexController
    {
        /// <summary>
        ///  获取菜单信息
        /// </summary>
        /// <param name="category">菜单类型</param>
        /// <returns></returns>       
        [HttpGet("Menu")]
        public ApiResult Menu(string category)
        {
            var result = new ApiResult();
            try
            {
                result.data = new TBActionService().FindAllList() ; 
            }
            catch (Exception ex)
            {
                result.code = ApiConstant.QUERY_ERROR_CODE;
                result.msg = ex.Message;
            }
            return result;
        }
    }
}

最终成果

 

(本文完)

标签:System,返回,分层,中介,response,管理软件,new,using,public
From: https://www.cnblogs.com/randytech/p/16657396.html

相关文章

  • 房产中介管理软件第4课:ORM框架SqlSugar配置
    本文只做SqlSugar的配置,具体功能还要到实际使用。 1、Nuget安装SqlSugarCore到项目2、假如我们有个表,TBAction3、建立对应的类文件,SqlSugar支持DBFirst和CodeFir......
  • 房产中介管理软件第1天:为什么要重构下房产中介管理软件
    以前维护过公司的一个房地产中介管理软件,使用的架构是C#.NetFramework4.0+WebForm+NHibernate,数据库是SQLServer2008,前端使用的JQuery,权限验证使用的是Session......
  • 重学TCP/IP系列(1):分层
    TCP/IP的起源TCP/IP协议起源于60年代末美国政府资助的一个分组交换网络研究项目,到90年代已发展为计算机之间最常用的组网形式。它成为被称作Internet的基础,该广域网(WAN)......
  • docker实战教程(七):镜像的分层概念
    联合文件系统(UnionFS)联合文件系统是一种分层、轻量级并且高性能的文件系统,它支持对文件系统的修改作为一次提交来一层层的叠加,同时可以将不同目录挂载到同一个虚拟文件系......
  • 中介者模式
    抽象中介者(Mediator):抽象中介者角色定义统一的接口,用于各同事角色之间的通信。抽象同事类(Colleague):每一个同事角色都知道中介者角色,而且与其它的同事角色通信的时候,一定......
  • 架构分层:我们为什么一定要这么做?
    在系统从0到1的阶段,为了让系统快速上线,我们通常是不考虑分层的。但是随着业务越来越复杂,大量的代码纠缠在一起,会出现逻辑不清晰、各模块相互依赖、代码扩展性差、改动......
  • 文献管理软件zotero | 下载安装使用与配置分享
    前言最开始阅读文献是使用readpaper平台,在线翻译、做笔记、文献管理都很方便,具体使用可以参考同济子豪兄和官方ReadPaper保姆级教程。但随着科研深入,readpaper的文献管理......
  • 中台服务分层架构
      1、接口适配层:方式一:动态调用RPC数据服务方式二:基于策略模式,动态加载dll实现,例如 ///<summary>///获得广告位置列表///</summary>......
  • ehcache3 分层存储选项
    参考文档ehcache3支持分层存储的概念,本文主要记录不同选项的配置和最佳时间。当在一个cache中,除了堆这一层外还有其它分层是,会有以下是事情发生。在往jvm堆缓存区域外......
  • 最好用的wifi管理软件
    如果您需要一款工具更好地管理您的wifi信号,那么wifiexplorerpro是您的不错选择!wifiexplorer可以查看周围所有WiFi信号源的详细报销,包括SSID名称,MAC地址,设备制造商,信号强......