1

基於示例MVC5項目,我試圖學習處理遷移的正確方法。獲取多個DbContexts以使用遷移相同的數據庫

在根目錄中我有一個名爲「DbContexts」與兩個Contextes的文件夾。

第一招:IdentityContext.cs

public class IdentityContext : IdentityDbContext<ApplicationUser> 
{ 
    public IdentityContext() 
     : base("DefaultConnection") 
    { } 
} 

然後我有一個名爲IdentityMigrations文件夾與Configuration.cs

internal sealed class Configuration : DbMigrationsConfiguration<TryFive.Web.DbContexts.IdentityContext> 
{ 
    public Configuration() 
    { 
     AutomaticMigrationsEnabled = true; 
     MigrationsDirectory = @"DbContexts\IdentityMigrations"; 
    } 

    protected override void Seed(TryFive.Web.DbContexts.IdentityContext context) 
    { 
     // This method will be called after migrating to the latest version. 

     // You can use the DbSet<T>.AddOrUpdate() helper extension method 
     // to avoid creating duplicate seed data. E.g. 
     // 
     // context.People.AddOrUpdate(
     //  p => p.FullName, 
     //  new Person { FullName = "Andrew Peters" }, 
     //  new Person { FullName = "Brice Lambson" }, 
     //  new Person { FullName = "Rowan Miller" } 
     // ); 
     // 
    } 
} 

然後,我有類似的性質MyContexts。

當我嘗試運行「更新-數據庫」命令,我收到此錯誤信息:The type 'TryFive.Web.DbContexts.IdentityContext' does not inherit from 'System.Data.Entity.Migrations.DbMigrationsConfiguration'. Migrations configuration types must extend from 'System.Data.Entity.Migrations.DbMigrationsConfiguration'.

關於如何解決此問題的任何想法或更好的方式來做到這一點的DbContext東西?

回答

2

建議:如果你只是做一個示例項目來學習如你所說的遷移,堅持一個DbContext。保持簡單 - 將您的實體合併到一個DbContext中,該DbContext繼承自IdentityDbContext<ApplicationUser>

刪除您創建的現有遷移文件夾 - 並在刪除第二個DbContext後重新啓用「enable-migrations」。這將幫助您繼續學習遷移,而不是學習如何在一個項目中使用兩個DbContext。

此外,@Lajos,我不確定你正在談論哪個MVC,但我的DbContext從未從DbMigrationsConfiguration繼承 - 它們從DbContext或IdentityDbContext繼承。您所指的是在項目上發佈「enable-migrations」時生成的MigrationsConfiguration類。它用於生成遷移和播種數據。

+0

好的,你在說可以將我的模型添加到默認的DbContext中嗎?我見過的每個示例都將ASP.NET Identity保留爲默認值,然後創建自己的調用相同數據庫的DbContext,並且遇到問題,告訴Migrations同時接受這兩個DbContext。 – Kaleet

+0

是的,它應該沒問題。他們只是給你一個默認的DbContext開箱 - 你可以根據需要修改它,但你不需要創建第二個。我已經看過一些關於使用獨立IdentityContext和其他上下文的文章,但對我來說,它只是過於複雜,除非你正在處理某些場景。 – Jack

相關問題