zoukankan      html  css  js  c++  java
  • 【无私分享:ASP.NET CORE 项目实战(第十二章)】添加对SqlServer、MySql、Oracle的支持

    目录索引 

    【无私分享:ASP.NET CORE 项目实战】目录索引

     

    简介

      

      增加对多数据库的支持,并不是意味着同时对多种数据库操作,当然,后面,我们会尝试同时对多种数据库操作,这可能需要多个上下文,暂且不论。分布式数据库,我们采用的是阿里云的Mycat,这个后面会更新出来。我们今天的场景是:我们的项目可能是在windows上开发的使用的是SqlServer,我们要发布到linux上,SqlServer 2017 据说是支持liunx的,但是还没出... 当然不是说 SqlServer 就不能装在liunx上,但是我们的Liunx服务器可能已经安装了MySql或 Oracle,我们希望使用现有的,又或者是,我们需要切换数据库。那么,我们需要可以随时切换数据库的支持。

      

    添加NuGet包,注册服务

       使用SqlServer数据库,这个官方有详细的步骤和解释,可以参考:https://docs.efproject.net/en/latest/providers/sql-server/index.html ,我们简单介绍一下

      在 【(第四章)】Code First 创建数据库和数据表 中,我们使用的就是SqlServer,我们新建了一个数据上下文 ApplicationDbContext

      然后在 Startup.cs 的 ConfigureServices(IServiceCollection services) 中,我们作为一个服务注册了上下文对象:

        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));

      

      在使用 UseSqlServer() 的时候,我们在 project.json 中添加了依赖包:Microsoft.EntityFrameworkCore.SqlServer

       

      那么,如何添加对Mysql的支持呢,在2016年8月24日,Mysql 官方出了第一版对 EntityFrameworkCore 支持的依赖包 (MySql.Data.EntityFrameworkCore 7.0.4-IR-191),这个我第一时间就尝试过,有少许问题,因为刚出,资料非常少,也几乎没多少用过的,也可能是有Bug,也可能是我自身的原因,不管什么原因,我还是一直用 官方没出之前的 第三方的依赖,今天,我们就是用 这个 依赖包作为演示,当然,大家可以使用官方的,对于使用,因为我们使用的是EF,所以在操作上没什么太大的区别,也可以随时切换。

      首先,我们引入这个包 Pomelo.EntityFrameworkCore.MySql,NuGet:Install-Package Pomelo.EntityFrameworkCore.MySql

      使用非常简单,跟上面的 SqlServer 一样,我们注册上下文(Startup.cs):

      services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));

      对了,就是把 UseSqlServer()改成 UseMySql()

      Oracle的官方也没出,也没发现很好的第三方,我们这里就先不介绍了,等养肥了。

     

    修改配置文件,实现切换

       我们上面实现了 EntityFrameworkCore 对两种数据库的支持,那么,我们总不能每次切换数据库都要 修改 Startup.cs 再编译生成吧,我们应该做一个类似开关之类的,可以实现发布完成的项目的数据库的切换。

      这里,我用的是配置文件。

      我们在 【(第八章)】读取配置文件(二) 读取自定义配置文件 中介绍了,如何使用自定义配置文件 siteconfig.json

      并且我们写了一个读取自定义配置文件的方法 GetAppSettings<T>(string key),这个方法,我稍微做了修改,增加了一个参数,可以读取任意的自定义配置文件,同时增加了对集合的读取(MyCat分布式数据库的时候读取节点会用到),这里把修改后的给大家贴一下:

      

      public class AppConfigurtaionServices
      {
        /// <summary>
        /// 获取自定义配置文件配置
        /// </summary>
        /// <typeparam name="T">配置模型</typeparam>
        /// <param name="key">根节点</param>
        /// <param name="configPath">配置文件名称</param>
        /// <returns></returns>
        public T GetAppSettings<T>(string key,string configPath= "siteconfig.json") where T:class,new()
        {
          IConfiguration config = new ConfigurationBuilder()
                      .Add(new JsonConfigurationSource { Path= configPath, ReloadOnChange=true })
                      .Build();

          var appconfig= new ServiceCollection()
                    .AddOptions()
                    .Configure<T>(config.GetSection(key))
                    .BuildServiceProvider()
                    .GetService<IOptions<T>>()
                    .Value;

          return appconfig;
        }
        /// <summary>
        /// 获取自定义配置文件配置(异步方式)
        /// </summary>
        /// <typeparam name="T">配置模型</typeparam>
        /// <param name="key">根节点</param>
        /// <param name="configPath">配置文件名称</param>
        /// <returns></returns>
        public async Task<T> GetAppSettingsAsync<T>(string key, string configPath = "siteconfig.json") where T : class, new()
        {
          IConfiguration config = new ConfigurationBuilder()
                        .Add(new JsonConfigurationSource { Path = configPath, ReloadOnChange = true })
                        .Build();

          var appconfig = new ServiceCollection()
                    .AddOptions()
                    .Configure<T>(config.GetSection(key))
                    .BuildServiceProvider()
                    .GetService<IOptions<T>>()
                    .Value;

          return await Task.Run(() => appconfig);
        }

        /// <summary>
        /// 获取自定义配置文件配置
        /// </summary>
        /// <typeparam name="T">配置模型</typeparam>
        /// <param name="key">根节点</param>
        /// <param name="configPath">配置文件名称</param>
        /// <returns></returns>
        public List<T> GetListAppSettings<T>(string key, string configPath = "siteconfig.json") where T : class, new()
        {
          IConfiguration config = new ConfigurationBuilder()
                        .Add(new JsonConfigurationSource { Path = configPath, ReloadOnChange = true })
                        .Build();

          var appconfig = new ServiceCollection()
                     .AddOptions()
                     .Configure<List<T>>(config.GetSection(key))
                     .BuildServiceProvider()
                     .GetService<IOptions<List<T>>>()
                     .Value;

          return appconfig;
        }
        /// <summary>
        /// 获取自定义配置文件配置(异步方式)
        /// </summary>
        /// <typeparam name="T">配置模型</typeparam>
        /// <param name="key">根节点</param>
        /// <param name="configPath">配置文件名称</param>
        /// <returns></returns>
        public async Task<List<T>> GetListAppSettingsAsync<T>(string key, string configPath = "siteconfig.json") where T : class, new()
        {
          IConfiguration config = new ConfigurationBuilder()
                        .Add(new JsonConfigurationSource { Path = configPath, ReloadOnChange = true })
                        .Build();

          var appconfig = new ServiceCollection()
                      .AddOptions()
                      .Configure<List<T>>(config.GetSection(key))
                      .BuildServiceProvider()
                      .GetService<IOptions<List<T>>>()
                      .Value;

          return await Task.Run(() => appconfig);
        }
      }

      我们修改一下我们的配置文件siteconfig.json :添加一个数据库选择的配置

      

      

      我们在平台检测类(没有的也可以自己新建一个)中,增加一个类用于检测数据库配置:internal class DataBaseProvider { }

      

      

      我们通过我们上面的读取配置文件的方法 读取 我们的配置:

      private ApplicationConfiguration dataBaserProvider = new Services.ConfigServices.AppConfigurtaionServices().GetAppSettings<ApplicationConfiguration>("siteconfig");

       

      读取数据库类型:

      public bool _isSqlServer
      {
        get
          {
            return dataBaserProvider.DataBase.ToLower() == "mssql";
          }

      }

      public bool _isMySql
      {
        get
          {
            return dataBaserProvider.DataBase.ToLower() == "mysql";
          }
      }

      public bool _isOracle
      {
        get
          {
            return dataBaserProvider.DataBase.ToLower() == "oracle";
          }
      }

      好了,我们回到我们的 Startup.cs

      首先,我们实例化一下我们这个类:

      

      修改 ConfigureServices(IServiceCollection services) 方法的 上下文注册服务:

      

      OK,这样我们就很简陋的实现了切换,我们来测试一下:

      首先使用SqlServer:siteconfig.json : "DataBase": "MSSQL"

      dotnet ef database update

      

      使用MySql:siteconfig.json : "DataBase": "MYSQL"

      dotnet ef database update

      

      好了,到这里就结束了,虽然简陋,给大家提供一下思路。

     

    希望跟大家一起学习Asp.net Core 

    刚开始接触,水平有限,很多东西都是自己的理解和翻阅网上大神的资料,如果有不对的地方和不理解的地方,希望大家指正!

    虽然Asp.net Core 现在很火热,但是网上的很多资料都是前篇一律的复制,所以有很多问题我也暂时没有解决,希望大家能共同帮助一下!

     

    原创文章 转载请尊重劳动成果 http://yuangang.cnblogs.com

     

  • 相关阅读:
    人生之清单(list of life)
    grpc编译错误解决
    windows tensorflow 版本与升级
    PermissionError: [Errno 13] in python
    经典分析--HTTP协议
    介绍 JSON
    Json 不同语言的使用
    JSON标准格式
    JSON 数据格式
    SKINTOOL 系统不能正常运行
  • 原文地址:https://www.cnblogs.com/yuangang/p/5828545.html
Copyright © 2011-2022 走看看