1. 程式人生 > >OsharpNS輕量級.net core快速開發框架簡明入門教程-多上下文配置(多個數據庫的使用)

OsharpNS輕量級.net core快速開發框架簡明入門教程-多上下文配置(多個數據庫的使用)

asi nag eve ble pro rpo 通過 現實 readonly

OsharpNS輕量級.net core快速開發框架簡明入門教程

教程目錄

  1. 從零開始啟動Osharp

    1.1. 使用OsharpNS項目模板創建項目

    1.2. 配置數據庫連接串並啟動項目

    1.3. OsharpNS.Swagger使用實例(登錄和授權)

    1.4. Angular6的前端項目啟動

  2. Osharp代碼生成器的使用

    2.1 生成器的使用

    2.2 生成代碼詳解(如何自己實現業務功能)

  3. Osharp部分模塊使用

    3.1 Osharp.Redis使用

    3.2 Osharp.Hangfire使用

    3.3 Osharp.Permissions使用

  4. Osharp深度學習和使用

    4.1 切換數據庫(從SqlServer改為MySql)

    4.2 多上下文配置(多個數據庫的使用)

    4.3. 自定義模塊的定義(Senparc.Weixin的使用)

    4.4. 繼續學習中....

OsharpNS官方資源
項目地址:https://github.com/i66soft/osharp-ns20
演示地址:https://www.osharp.org 直接使用QQ登錄可以查看效果
文檔地址:https://docs.osharp.org 正在完善中....
發布博客:https://www.cnblogs.com/guomingfeng/p/osharpns-publish.html 大神看這個文檔應該就能跑起來,從零開始啟動Osharp基於此文檔完成
VS生成器插件:https://marketplace.visualstudio.com/items?itemName=LiuliuSoft.osharp
官方交流QQ群:85895249

多上下文配置(多個數據庫的使用)

  1. 項目CanDoo.Test.Core通過Nuget添加對包OsharpNS的引用

  2. 配置文件appsettings.Development.json中添加OSharp:DbContexts:MySqlAudit連接參數

"MySqlAudit": {
 "DbContextTypeName": "CanDoo.Test.Core.Entity.MySqlAuditDbContext,OSharp.EntityFrameworkCore",//這裏要註意下
 "ConnectionString": "Server=localhost;Port=3306;UserId=root;Password=******;Database=CanDoo.Test.Audit;charset=‘utf8‘;Allow User Variables=True",
 "DatabaseType": "MySql",
 "LazyLoadingProxiesEnabled": true,
 "AuditEntityEnabled": true,
 "AutoMigrationEnabled": true
 }
  1. 新建CanDoo.Test.Core.Entity.MySqlAuditDbContext上下文
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using OSharp.Entity;

namespace CanDoo.Test.Core.Entity
{
    public class MySqlAuditDbContext : DbContextBase
    {
        public MySqlAuditDbContext(DbContextOptions options, IEntityManager entityManager, IServiceProvider serviceProvider) : base(options, entityManager, serviceProvider)
        {

        }
    }
}
  1. 創建CanDoo.Test.Web.Startups.MySqlAuditMigrationPack遷移模塊
using System;
using OSharp.Entity;
using OSharp.Entity.MySql;
using CanDoo.Test.Core.Entity;
using CanDoo.Test.Web.Startups;

namespace CanDoo.Test.Web.Startups
{
    /// <summary>
    /// MySqlAudit遷移模塊
    /// </summary>
    public class MySqlAuditMigrationPack : MigrationPackBase<MySqlAuditDbContext>
    {
        /// <summary>
        /// 獲取 模塊啟動順序,模塊啟動的順序先按級別啟動,級別內部再按此順序啟動,
        /// 級別默認為0,表示無依賴,需要在同級別有依賴順序的時候,再重寫為>0的順序值
        /// </summary>
        public override int Order => 2;

        protected override DatabaseType DatabaseType { get; } = DatabaseType.MySql;

        protected override MySqlAuditDbContext CreateDbContext(IServiceProvider scopedProvider)
        {
            return new MySqlAuditDesignTimeDbContextFactory(scopedProvider).CreateDbContext(new string[0]);
        }

        //針對多庫連接的,需要在EntityConfiguration部分增加以下代碼,指定DbContext
        //public override Type DbContextType { get; } = typeof(MySqlAuditDbContext);
    }
}
using System;
using System.Reflection;

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using OSharp.Core.Options;
using OSharp.Data;
using OSharp.Entity;
using OSharp.Exceptions;
using OSharp.Extensions;
using OSharp.Reflection;
using CanDoo.Test.Core.Entity;

namespace CanDoo.Test.Web.Startups
{
    public class MySqlAuditDesignTimeDbContextFactory : DesignTimeDbContextFactoryBase<MySqlAuditDbContext>
    {
        private readonly IServiceProvider _serviceProvider;

        public MySqlAuditDesignTimeDbContextFactory()
        { }

        public MySqlAuditDesignTimeDbContextFactory(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public override string GetConnectionString()
        {
            if (_serviceProvider == null)
            {
                IConfiguration configuration = Singleton<IConfiguration>.Instance;
                string str = configuration["OSharp:DbContexts:MySqlAudit:ConnectionString"]; //這裏是配置節點的信息 記得修改
                return str;
            }
            OsharpOptions options = _serviceProvider.GetOSharpOptions();
            OsharpDbContextOptions contextOptions = options.GetDbContextOptions(typeof(DefaultDbContext));
            if (contextOptions == null)
            {
                throw new OsharpException($"上下文“{typeof(MySqlAuditDbContext)}”的配置信息不存在");
            }
            return contextOptions.ConnectionString;
        }

        public override IEntityManager GetEntityManager()
        {
            if (_serviceProvider != null)
            {
                return _serviceProvider.GetService<IEntityManager>();
            }
            IEntityConfigurationTypeFinder typeFinder = new EntityConfigurationTypeFinder(new AppDomainAllAssemblyFinder());
            IEntityManager entityManager = new EntityManager(typeFinder);
            entityManager.Initialize();
            return entityManager;
        }

        public override bool LazyLoadingProxiesEnabled()
        {
            if (_serviceProvider == null)
            {
                IConfiguration configuration = Singleton<IConfiguration>.Instance;
                return configuration["OSharp:DbContexts:MySqlAudit:LazyLoadingProxiesEnabled"].CastTo(false); //這裏是配置節點的信息 記得修改
            }
            OsharpOptions options = _serviceProvider.GetOSharpOptions();
            OsharpDbContextOptions contextOptions = options.GetDbContextOptions(typeof(DefaultDbContext));
            if (contextOptions == null)
            {
                throw new OsharpException($"上下文“{typeof(MySqlAuditDbContext)}”的配置信息不存在");
            }

            return contextOptions.LazyLoadingProxiesEnabled;
        }

        public override DbContextOptionsBuilder UseSql(DbContextOptionsBuilder builder, string connString)
        {
            string entryAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            Console.WriteLine($"entryAssemblyName: {entryAssemblyName}");
            return builder.UseMySql(connString, b => b.MigrationsAssembly(entryAssemblyName));
        }
    }
}
  1. 審計功能相關的表使用新的上下文,CanDoo.Test.EntityConfiguration.Systems中Audit開頭的3個文件都增加以下配置代碼,指定使用MySqlAuditDbContext
public override Type DbContextType { get; } = typeof(MySqlAuditDbContext); //新增此行代碼 指定使用MySqlAuditDbContext 未指定的還是使用DefaultDbContext
using System;
using System.Collections.Generic;
using System.Text;
using CanDoo.Test.Core.Entity;
using CanDoo.Test.Systems.Entities;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using OSharp.Entity;

namespace CanDoo.Test.EntityConfiguration.Systems
{
    public class AuditPropertyConfiguration : EntityTypeConfigurationBase<AuditProperty, Guid>
    {
        public override Type DbContextType { get; } = typeof(MySqlAuditDbContext); //新增此行代碼 指定使用MySqlAuditDbContext 未指定的還是使用DefaultDbContext

        /// <summary>
        /// 重寫以實現實體類型各個屬性的數據庫配置
        /// </summary>
        /// <param name="builder">實體類型創建器</param>
        public override void Configure(EntityTypeBuilder<AuditProperty> builder)
        {
            builder.HasIndex(m => m.AuditEntityId);
            builder.HasOne(m => m.AuditEntity).WithMany(n => n.Properties).HasForeignKey(m => m.AuditEntityId);
        }
    }
}
  1. 在程序包管理控制臺中執行Add-Migration -Context MySqlAuditDbContext newDbContext,創建遷移腳本,因系統中存在2個DbContext,所以需要指定上下文-Context MySqlAuditDbContext

  2. 在程序包管理控制臺中執行update-database -Context MySqlAuditDbContext

  3. 至此,數據庫中新生成了一個庫,庫中包含用於審計功能的三張表

OsharpNS輕量級.net core快速開發框架簡明入門教程-多上下文配置(多個數據庫的使用)