問題的提出疑俭,在實(shí)際項(xiàng)目中,根據(jù)不同用戶的需要婿失,可能需要更改使用的數(shù)據(jù)庫(kù)類型钞艇,比如,在某個(gè)項(xiàng)目中使用SqlServer豪硅,而在另一個(gè)項(xiàng)目中需要使用Sqlite哩照。在使用EF6時(shí),可以通過更換配置文件中的provider更改數(shù)據(jù)源懒浮,可是EF core似乎是在代碼中進(jìn)行注冊(cè)的:
builder.UseSqlServer(options.ExistingConnection);
如何更改為其它數(shù)據(jù)庫(kù)飘弧?沒有發(fā)現(xiàn)很好的辦法识藤,只能是修改StartUp,在編碼中注冊(cè)切換。
1次伶、安裝Microsoft.EntityFrameworkCore.Sqlite
2痴昧、修改
using Abp.Modules;
using Abp.Reflection.Extensions;
using Microsoft.EntityFrameworkCore;
using Zl.TangPoem.STD;
namespace ZL.TangPoem.STD.EF
{
[DependsOn(
typeof(PoemCoreModule),
typeof(AbpEntityFrameworkCoreModule))]
public class PoemDataModule : AbpModule
{
/* 在單元測(cè)試時(shí),使用EF Core的內(nèi)存數(shù)據(jù)庫(kù)冠王,不需要進(jìn)行數(shù)據(jù)庫(kù)注冊(cè) */
public bool SkipDbContextRegistration { get; set; }
//增加sqlite sqlserver切換
public string DbType { get; set; }
/// <summary>
/// 初始化時(shí)注冊(cè)DbContext
/// </summary>
public override void PreInitialize()
{
if (!SkipDbContextRegistration)
{
if (DbType == "sqlite")
{
Configuration.Modules.AbpEfCore().AddDbContext<PoemDbContext>(options =>
{
var builder = options.DbContextOptions;
if (options.ExistingConnection != null)
{
builder.UseSqlite(options.ExistingConnection);
}
else
{
builder.UseSqlite(options.ConnectionString);
}
});
}
else
{
Configuration.Modules.AbpEfCore().AddDbContext<PoemDbContext>(options =>
{
var builder = options.DbContextOptions;
if (options.ExistingConnection != null)
{
builder.UseSqlServer(options.ExistingConnection);
}
else
{
builder.UseSqlServer(options.ConnectionString);
}
});
}
}
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(PoemDataModule).GetAssembly());
}
}
}
3赶撰、修改調(diào)用模塊,增加數(shù)據(jù)庫(kù)類型設(shè)置:
using System.Reflection;
using Zl.TangPoem.STD;
using ZL.TangPoem.STD.Application;
using ZL.TangPoem.STD.EF;
namespace ZL.TangPoem.Core.ConsoleClient
{
[DependsOn(typeof(PoemCoreModule),
typeof(PoemDataModule),
typeof(PoemApplicationModule))]
public class PoemConsoleClientModule : AbpModule
{
/// <summary>
/// 增加數(shù)據(jù)庫(kù)選項(xiàng)
/// </summary>
/// <param name="dataModule"></param>
public PoemConsoleClientModule(PoemDataModule dataModule)
{
dataModule.DbType = "sqlite";
}
public override void PreInitialize()
{
var conn = @"Data Source=D:\Poem\Sqlite\Poem.db";
Configuration.DefaultNameOrConnectionString = conn;
// Configuration.DefaultNameOrConnectionString = "Server=localhost; Database=PoemNew; Trusted_Connection=True;";
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
}
這種方式并不是很好柱彻,因?yàn)樵黾恿藢?duì)兩種數(shù)據(jù)庫(kù)類型的依賴豪娜,另外,如果再增加數(shù)據(jù)庫(kù)類型哟楷,仍然要修改代碼瘤载,達(dá)不到動(dòng)態(tài)更換的目的。應(yīng)該有更好的辦法卖擅,不過目前還沒有發(fā)現(xiàn)鸣奔。