在做項目時,需要將某一些功能的實體建立在另一個數(shù)據(jù)庫中,連接不同的數(shù)據(jù)庫用以存儲記錄。通過查找資料,實現(xiàn)EF Core上下文。
下面是實現(xiàn)上下文后的解決方案的目錄:
1.UpAndDownDbContext
2.UpAndDownDbContextConfigurer
3.UpAndDownDbContextFactory
以上三個文件為第二個數(shù)據(jù)庫的相關遷移和配置
4.新增MyConnectionStringResolver,根據(jù)不同的類型查找不同的數(shù)據(jù)庫連接串
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設置另一個數(shù)據(jù)庫的連接串
7.在MyTestProjectConsts和SCMConsts中分別建立常量
以上就是實現(xiàn)數(shù)據(jù)庫上下文的所有的相關配置過程。
最后測試一波
執(zhí)行數(shù)據(jù)庫遷移 ,由于配置了上下文所以在遷移時要指定DbContext:Add-Migration (遷移名稱) -c UpAndDownDbContext(或MyTestProjectDbContext)。
若是不指定DbContext則會出現(xiàn)錯誤: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.
整個的配置就完成了。
本文摘自 :https://www.cnblogs.com/