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