Asp.Net Core Api架构设计(二)之多数据库支持

一、引言

本架构支持Sqlite,SqlServer,MySQL,Oracle,其他数据库自行配置。
Sqlite
关系型嵌入式数据库,只需引用一个文件即可读写数据库文件,不需要安装服务框架。查询受硬盘读写速度影响(现在的服务器SSD硬盘速度极快),如果你只是要做一个内容发布类项目,它的优势相当明显。推荐使用SQLite Expert管理数据库。
SQL Server
同Sqlite一样同属关系型数据库,安装比较麻烦,对服务器要求较高。但是支持分布式等Sqlite不具备的特性,与ASP.NET能很好的结合起来。
MySql
MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件之一。
MySQL是一种关系型数据库管理系统,关系数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内,这样就增加了速度并提高了灵活性。
MySQL所使用的 SQL 语言是用于访问数据库的最常用标准化语言。MySQL 软件采用了双授权政策,分为社区版和商业版,由于其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,一般中小型网站的开发都选择 MySQL 作为网站数据库。
Oracle
Oracle Database,又名Oracle RDBMS,或简称Oracle。是甲骨文公司的一款关系数据库管理系统。它是在数据库领域一直处于领先地位的产品。可以说Oracle数据库系统是目前世界上流行的关系数据库管理系统,系统可移植性好、使用方便、功能强,适用于各类大、中、小、微机环境。它是一种高效率、可靠性好的、适应高吞吐量的数据库方案。

1、appSetting.json配置

  // 请配置MainDB为你想要的主库的ConnId值,并设置对应的Enabled为true;
  // *** 单库操作,把 MutiDBEnabled 设为false ***;
  // *** 多库操作,把 MutiDBEnabled 设为true,其他的从库也为true **;
  "MainDB": "WMBLOG_SQLITE", //当前项目的主库,所对应的连接字符串的Enabled必须为true
  "MutiDBEnabled": false, //是否开启多库
  "DBS": [
    /*
      MySql = 0,
      SqlServer = 1,
      Sqlite = 2,
      Oracle = 3
    */
    {
      "ConnId": "WMBLOG_SQLITE",
      "DBType": 2,
      "Enabled": true,
      "Connection": "WMBlog.db" //只写数据库名就行,我会拼接字符串
    },
    {
      "ConnId": "BLOG_MSSQL",
      "DBType": 1,
      "Enabled": true,
      "Connection": "Server=.;Database=BlogDB;User ID=sa;Password=123456;",
      "ProviderName": "System.Data.SqlClient"
    },
    {
      "ConnId": "BLOG_MYSQL",
      "DBType": 0,
      "Enabled": true,
      "Connection": "Server=localhost; Port=3306;Stmt=; Database=BlogDB; Uid=root; Pwd=123456;"
    },
    {
      "ConnId": "BLOG_ORACLE",
      "DBType": 3,
      "Enabled": false,
      "Connection": "Provider=OraOLEDB.Oracle; Data Source=BlogDB; User Id=sss; Password=123456;"
    }
  ]

2、提供读取配置的帮助类

在Common项目添加Helper文件夹,添加如下帮助类:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Linq;

namespace BlogStudy.Common
{
    /// <summary>
    /// appsettings.json操作类
    /// </summary>
    public class AppsettingHelper
    {
        static IConfiguration Configuration { get; set; }

        public AppsettingHelper(string contentPath)
        {
            string Path = "appsettings.json";
            Configuration = new ConfigurationBuilder()
               .SetBasePath(contentPath)
               .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//这样的话,可以直接读目录里的json文件,而不是 bin 文件夹下的,所以不用修改复制属性
               .Build();
        }

        /// <summary>
        /// 封装要操作的字符
        /// </summary>
        /// <param name="sections">节点配置</param>
        /// <returns></returns>
        public static string GetSectionString(params string[] sections)
        {
            try
            {
                if (sections.Any())
                {
                    return Configuration[string.Join(":", sections)];
                }
            }
            catch (Exception) { }
            return "";
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace BlogStudy.Common.Helper
{
    /// <summary>
    /// 
    /// </summary>
    public static class UtilConvert
    {

        /// <summary>
        /// 对象转Int
        /// </summary>
        /// <param name="thisValue"></param>
        /// <returns></returns>
        public static int ObjToInt(this object thisValue)
        {
            int reval = 0;
            if (thisValue == null) return 0;
            if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval))
            {
                return reval;
            }
            return reval;
        }
        /// <summary>
        /// 对象转Int
        /// </summary>
        /// <param name="thisValue"></param>
        /// <param name="errorValue"></param>
        /// <returns></returns>
        public static int ObjToInt(this object thisValue, int errorValue)
        {
            int reval = 0;
            if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval))
            {
                return reval;
            }
            return errorValue;
        }

        /// <summary>
        /// 对象转double
        /// </summary>
        /// <param name="thisValue"></param>
        /// <returns></returns>
        public static double ObjToMoney(this object thisValue)
        {
            double reval = 0;
            if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval))
            {
                return reval;
            }
            return 0;
        }
        /// <summary>
        /// 对象转double
        /// </summary>
        /// <param name="thisValue"></param>
        /// <param name="errorValue"></param>
        /// <returns></returns>
        public static double ObjToMoney(this object thisValue, double errorValue)
        {
            double reval = 0;
            if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval))
            {
                return reval;
            }
            return errorValue;
        }
        /// <summary>
        /// 对象转String
        /// </summary>
        /// <param name="thisValue"></param>
        /// <returns></returns>
        public static string ObjToString(this object thisValue)
        {
            if (thisValue != null) return thisValue.ToString().Trim();
            return "";
        }
        /// <summary>
        /// 对象转String
        /// </summary>
        /// <param name="thisValue"></param>
        /// <param name="errorValue"></param>
        /// <returns></returns>
        public static string ObjToString(this object thisValue, string errorValue)
        {
            if (thisValue != null) return thisValue.ToString().Trim();
            return errorValue;
        }
        /// <summary>
        /// 对象转Decimal
        /// </summary>
        /// <param name="thisValue"></param>
        /// <returns></returns>
        public static Decimal ObjToDecimal(this object thisValue)
        {
            Decimal reval = 0;
            if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval))
            {
                return reval;
            }
            return 0;
        }
        /// <summary>
        /// 对象转Decimal
        /// </summary>
        /// <param name="thisValue"></param>
        /// <param name="errorValue"></param>
        /// <returns></returns>
        public static Decimal ObjToDecimal(this object thisValue, decimal errorValue)
        {
            Decimal reval = 0;
            if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval))
            {
                return reval;
            }
            return errorValue;
        }
        /// <summary>
        /// 对象转时间
        /// </summary>
        /// <param name="thisValue"></param>
        /// <returns></returns>
        public static DateTime ObjToDate(this object thisValue)
        {
            DateTime reval = DateTime.MinValue;
            if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
            {
                reval = Convert.ToDateTime(thisValue);
            }
            return reval;
        }
        /// <summary>
        /// 对象转时间
        /// </summary>
        /// <param name="thisValue"></param>
        /// <param name="errorValue"></param>
        /// <returns></returns>
        public static DateTime ObjToDate(this object thisValue, DateTime errorValue)
        {
            DateTime reval = DateTime.MinValue;
            if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
            {
                return reval;
            }
            return errorValue;
        }
        /// <summary>
        /// 对象转bool
        /// </summary>
        /// <param name="thisValue"></param>
        /// <returns></returns>
        public static bool ObjToBool(this object thisValue)
        {
            bool reval = false;
            if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval))
            {
                return reval;
            }
            return reval;
        }
    }
}

在Common项目添加DB文件夹,添加如下帮助类:

using BlogStudy.Common.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace BlogStudy.Common.DB
{
    public class BaseDBConfig
    {
    	public static string CurrentDbConnId = "1";
    	
        public static List<MutiDBOperate> MutiConnectionString => MutiInitConn();

        /// <summary>
        /// 获取数据库配置
        /// </summary>
        /// <returns></returns>
        public static List<MutiDBOperate> MutiInitConn()
        {
            List<MutiDBOperate> listdatabase = new List<MutiDBOperate>();
            List<MutiDBOperate> listdatabaseSimpleDB = new List<MutiDBOperate>();
            //读取配置
            string dbConfigStr = AppsettingHelper.GetSectionString(new string[] { "DbConfig" }).ObjToString();
            DbConfig dbConfig = JsonConvert.DeserializeObject<DbConfig>(dbConfigStr);

            //链接字符串转换
            dbConfig.DBS.ForEach(a => listdatabase.Add(SpecialDbString(
                new MutiDBOperate()
                {
                    ConnId = a.ConnId,
                    Conn = a.Conn,
                    DbType = a.DbType
                })));

            //如果启用多库
            if (dbConfig.MutiDBEnabled || listdatabase.Count == 1)
            {
                return listdatabase;
            }

            //单库,只保留一个
            var dbFirst = listdatabase.FirstOrDefault(d => d.ConnId == dbConfig.MainDB);
            if (dbFirst == null)
            {
                dbFirst = dbConfig.DBS.FirstOrDefault();
            }
            listdatabaseSimpleDB.Add(dbFirst);
            return listdatabaseSimpleDB;
        }

        /// <summary>
        /// 链接字符串设置
        /// </summary>
        /// <param name="mutiDBOperate"></param>
        /// <returns></returns>
        private static MutiDBOperate SpecialDbString(MutiDBOperate mutiDBOperate)
        {
            if (mutiDBOperate.DbType == DataBaseType.Sqlite)
            {
                mutiDBOperate.Conn = $"DataSource=" + Path.Combine(Environment.CurrentDirectory, mutiDBOperate.Conn);
            }
            return mutiDBOperate;
        }
    }


    public enum DataBaseType
    {
        MySql = 0,
        SqlServer = 1,
        Sqlite = 2,
        Oracle = 3
    }
    public class MutiDBOperate
    {
        public string ConnId { get; set; }
        public string Conn { get; set; }
        public DataBaseType DbType { get; set; }
    }
    
    public class DbConfig
    {
        public string MainDB { get; set; }
        public bool MutiDBEnabled { get; set; }
        public List<MutiDBOperate> DBS { get; set; }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sufengmarket

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值