asp.net core + entity framework core 多數據庫類型支持實戰


根據微軟官方文檔的說法,有兩種方法可以實現在一個app中同時適應多種不同類型的數據庫,並且全部支持migrations操作。其一,使用兩個dbcontext;其二,修改migration文件,添加特定數據庫類型的Annotation。

本人在實際使用過程中發現,第二種情況幾乎很難調通,總是在migration操作時遭遇各種奇怪問題,而且這種操作似乎也不太”干凈“;第一種操作,一開始無論如何也調不通,后來發現是dbcontext的注入方式有問題,不能像默認模板生成的那樣使用options參數,而是應該使用空白的構造方法,具體代碼如下:

DbContext:

    public class ApplicationDbContext : IdentityDbContext
    {
        public DbSet<Location> Locations { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }

    public class PgDbContext : ApplicationDbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseNpgsql(Startup.Configuration.GetConnectionString("DefaultConnection"));
        }
    }

    public class MsDbContext : ApplicationDbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(Startup.Configuration.GetConnectionString("DefaultConnection"));
        }
    }

注意覆蓋的方法是OnConfiguring。

然后就是Startup中根據配置的數據庫類型注入不同的dbcontext:

        public void ConfigureServices(IServiceCollection services)
        {
            var dbType = Configuration.GetValue<string>("DbType");

            //多種數據庫支持
            if (dbType == "PGSQL")
                services.AddDbContext<ApplicationDbContext, PgDbContext>();
            else
                services.AddDbContext<ApplicationDbContext, MsDbContext>();

            services.AddDefaultIdentity<IdentityUser>(options => {
                options.SignIn.RequireConfirmedAccount = false;
            }).AddEntityFrameworkStores<ApplicationDbContext>();


            services.AddControllersWithViews();
            services.AddRazorPages();
        }

然后,別忘了,給不同的數據庫類型(dbcontext)建立不同的migration:

Add-Migration Initial -Context MsDbContext -OutputDir Migrations/Mssql

Add-Migration Initial -Context PgDbContext -OutputDir Migrations/Pssql

以上命令分別建立不同的migrations。

最后,在執行context.Database.Migrate()時,context就會根據數據庫類型自動尋找正確的migrations了。

關鍵:不再通過options參數構造dbcontext。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM