在做專案時,需要將某一些功能的實體建立在另一個數據庫中,連線不同的資料庫用以儲存記錄。通過查詢資料,實現EF Core上下文。

下面是實現上下文後的解決方案的目錄:

1.UpAndDownDbContext

2.UpAndDownDbContextConfigurer

3.UpAndDownDbContextFactory

以上三個檔案為第二個資料庫的相關遷移和配置

4.新增MyConnectionStringResolver,根據不同的型別查詢不同的資料庫連線串

5.在MyTestProjectEntityFrameworkModule檔案中新增部分程式碼,將MyConnectionStringResolver注入到Module中

namespace MyTestProject.EntityFrameworkCore
{
[DependsOn(
typeof(MyTestProjectCoreModule),
typeof(AbpZeroCoreEntityFrameworkCoreModule))]
public class MyTestProjectEntityFrameworkModule : AbpModule
{
/* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
public bool SkipDbContextRegistration { get; set; } public bool SkipDbSeed { get; set; } public override void PreInitialize()
{
#region 新增將計注入
Configuration.ReplaceService(typeof(IConnectionStringResolver), () =>
{
IocManager.IocContainer.Register(
Component.For<IConnectionStringResolver>()
.ImplementedBy<MyConnectionStringResolver>()
.LifestyleTransient()
);
});
#endregion if (!SkipDbContextRegistration)
{
Configuration.Modules.AbpEfCore().AddDbContext<MyTestProjectDbContext>(options =>
{
if (options.ExistingConnection != null)
{
MyTestProjectDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
MyTestProjectDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
}
#region 注入
// Configure workflow DbContext
Configuration.Modules.AbpEfCore().AddDbContext<UpAndDownDbContext>(options =>
{
if (options.ExistingConnection != null)
{
UpAndDownDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
UpAndDownDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
#endregion ////Dapper
//DapperExtensions.DapperExtensions.SqlDialect = new DapperExtensions.Sql.MySqlDialect();
} public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(MyTestProjectEntityFrameworkModule).GetAssembly());
} //public override void PostInitialize()
//{
// if (!SkipDbSeed)
// {
// SeedHelper.SeedHostDb(IocManager);
// }
//}
}
}

6.在appsettings.json設定另一個數據庫的連線串

7.在MyTestProjectConsts和SCMConsts中分別建立常量

以上就是實現資料庫上下文的所有的相關配置過程。

最後測試一波

執行資料庫遷移 ,由於配置了上下文所以在遷移時要指定DbContext:Add-Migration (遷移名稱) -c UpAndDownDbContext(或MyTestProjectDbContext)。

若是不指定DbContext則會出現錯誤:More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

整個的配置就完成了。