DbContext.cs 6.81 KB
using SqlSugar;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SqlSugar.DbConvert;

namespace RCS.Dal
{
    public class DbContext
    {
        #region 属性字段
        /// <summary>
        /// 默认架构(数据库名)
        /// </summary>
        public static string Scheme { get; set; }
        /// <summary>
        /// 存放各个数据库的SqlSugarScope,KEY是数据库名称,VALUE是SqlSugarScope
        /// </summary>
        public static Dictionary<string, SqlSugarScope> DbDictionary = new Dictionary<string, SqlSugarScope>();

        #endregion 属性字段

        /// <summary>
        /// SQL异常日志
        /// </summary>
        public static Action<string, string, bool> Log;

        #region 构造函数

        /// <summary>
        /// 功能描述:构造函数
        /// </summary>
        /// <param name="dalOptions">数据库配置</param>
        /// <param name="blnIsAutoCloseConnection">是否自动关闭连接</param>
        public static void Init(DalOptions dalOptions, bool isAutoCloseConnection = true)
        {
            if (dalOptions == null)
            {
                throw new ArgumentNullException("数据库配置实体为空!");
            }
            Scheme = dalOptions.Scheme;
            var moreSettings = new ConnMoreSettings()
            {
                //IsWithNoLockQuery = true,
                IsAutoRemoveDataCache = true
            };
            //设置自定义特性,也就是使用.NET默认的实体特性,不用SqlSugar的特性,避免循环引用
            var configureExternalServices = new ConfigureExternalServices()
            {
                //设置字段的特性
                EntityService = (property, column) =>
                {
                    //枚举
                    if ((property.DeclaringType?.Name.Contains("Protocol") ?? false) && (property.Name == "DataType" || property.Name == "DestDataType"))
                    {
                        column.DataType = "varchar(50)";
                        column.SqlParameterDbType = typeof(EnumToStringConvert);

                    }
                    var attributes = property.GetCustomAttributes(true);
                    //主键
                    if (attributes.Any(t => t is KeyAttribute))
                    {
                        column.IsPrimarykey = true;
                    }
                    //不映射到数据库
                    if (attributes.Any(t => t is NotMappedAttribute))
                    {
                        column.IsIgnore = true;
                    }
                    //数据库字段名
                    if (attributes.Any(t => t is ColumnAttribute))
                    {
                        var attr = attributes.First(t => t is ColumnAttribute) as ColumnAttribute;
                        if (!string.IsNullOrWhiteSpace(attr.Name))
                        {
                            column.DbColumnName = attr.Name;
                        }
                    }
                    //自增长
                    if (attributes.Any(t => t is DatabaseGeneratedAttribute))
                    {
                        var attr = attributes.First(t => t is DatabaseGeneratedAttribute) as DatabaseGeneratedAttribute;
                        if (attr.DatabaseGeneratedOption == DatabaseGeneratedOption.Identity)
                        {
                            column.IsIdentity = true;
                        }
                    }
                },
                //设置实体的特性
                EntityNameService = (type, entity) =>
                {
                    var attributes = type.GetCustomAttributes(true);
                    if (attributes.Any(t => t is TableAttribute))
                    {
                        var attr = attributes.First(t => t is TableAttribute) as TableAttribute;
                        entity.DbTableName = attr.Name;
                    }
                }
            };

            foreach (var dalOption in dalOptions.Options)
            {
                SqlSugarScope _Db = new SqlSugarScope(new ConnectionConfig()
                {
                    ConnectionString = dalOption.ConStr,
                    DbType = dalOption.Type,
                    IsAutoCloseConnection = isAutoCloseConnection,
                    //IsShardSameThread = true,
                    MoreSettings = moreSettings,
                    ConfigureExternalServices = configureExternalServices
                });
                if (dalOption.MonitorCommand)
                {
                    _Db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        //Console.WriteLine(sql+"\r\n");
                        //输出sql,查看执行sql
                        //5.0.8.2 获取无参数化 SQL
                        var sqlText = UtilMethods.GetSqlString(DbType.SqlServer, sql, pars);
                        Log?.Invoke("sqlText", sqlText + "\r\n", false);
                    };
                }
                DbDictionary.Add(dalOption.Scheme, _Db);
            }
        }

        #endregion 构造函数


        #region 根据实体类生成数据库表

        ///// <summary>
        ///// 功能描述:根据实体类生成数据库表
        ///// 作  者:beck.huang
        ///// 创建日期:2018-05-08 10:31:02
        ///// 任务编号:中餐
        ///// </summary>
        ///// <param name="blnBackupTable">是否备份表</param>
        ///// <param name="lstEntitys">指定的实体</param>
        //public void CreateTableByEntity<T>(bool blnBackupTable, params T[] lstEntitys) where T : class, new()
        //{
        //    Type[] lstTypes = null;
        //    if (lstEntitys != null)
        //    {
        //        lstTypes = new Type[lstEntitys.Length];
        //        for (int i = 0; i < lstEntitys.Length; i++)
        //        {
        //            lstTypes[i] = typeof(T);
        //        }
        //    }
        //    CreateTableByEntity(blnBackupTable, lstTypes);
        //}

        ///// <summary>
        ///// 功能描述:根据实体类生成数据库表
        ///// 作  者:beck.huang
        ///// 创建日期:2018-05-08 10:31:14
        ///// 任务编号:中餐
        ///// </summary>
        ///// <param name="blnBackupTable">是否备份表</param>
        ///// <param name="lstEntitys">指定的实体</param>
        //public void CreateTableByEntity(bool blnBackupTable, params Type[] lstEntitys)
        //{
        //    if (blnBackupTable)
        //    {
        //        _db.CodeFirst.BackupTable().InitTables(lstEntitys); //change entity backupTable
        //    }
        //    else
        //    {
        //        _db.CodeFirst.InitTables(lstEntitys);
        //    }
        //}

        #endregion 根据实体类生成数据库表


    }
}