ASP.Net MVC Entity Framework Error – More than one context type was found in the assembly ‘ProjectName’.

最近愛上了使用Entity Framework..
當我嘗試使用 “enable-migrations” 時出現以下的錯誤信息

More than one context type was found in the assembly ‘LocalIssuesWeb’.
To enable migrations for ‘LocalIssuesWeb.Models.ApplicationDbContext’, use Enable-Migrations -ContextTypeName LocalIssuesWeb.Models.ApplicationDbContext.
To enable migrations for ‘LocalIssuesWeb.DAL.LocalIssuesContext’, use Enable-Migrations -ContextTypeName LocalIssuesWeb.DAL.LocalIssuesContext.
More than one context type was found in the assembly

做了一會research之後發現是由於 ASP.Net IdentityApplicationDbContext和我自己定義給這個project的 Database Context不同所以出現的

解決方法十分簡單
我們需要分別為 ASP.Net IdentityApplicationDbContext和自己定期的Database context 執行migration
e.g.

Enable migration for ApplicationDBContext – create a folder inside migration folder named “ApplicationDBContext
enable-migrations -ContextTypeName [Context Name] -MigrationsDirectory Migrations\[想建立的Context Folder Name]

 enable-migrations -ContextTypeName ApplicationDBContext -MigrationsDirectory Migrations\ApplicationDBContext

More than one context type was found in the assembly

Entity Framework Migration Folder
add-migration

add-migrationConfigurationTypeName [Namespace e.g. LocalIssuesWeb.Migrations.ApplicationDBContext].ConfigurationInit user database

add-migration -ConfigurationTypeName LocalIssuesWeb.Migrations.ApplicationDBContext.Configuration "Init user database"

Add Migration
Update-database

update-database -ConfigurationTypeName [NameSpace].Configuration

update-database -ConfigurationTypeName LocalIssuesWeb.Migrations.ApplicationDBContext.Configuration

Update Database
現在ApplicationDBContext之後我們可以為自己建立的Database Context進行migration
和之前的指令差不多

enable-migrations -ContextTypeName LocalIssuesContext -MigrationsDirectory Migrations\LocalIssuesContext

add-migration

add-migration -ConfigurationTypeName LocalIssuesWeb.Migrations.LocalIssuesContext.Configuration "Init"

Update-database

update-database -ConfigurationTypeName LocalIssuesWeb.Migrations.LocalIssuesContext.Configuration

之後每當我們有更改ASP.Net Identity的class 時都要執行 ApplicationDbContextAdd-Migtration和Update-database
然而自己的Database model更新了便要更新自己的Database context.

Hope you find it useful

2 thoughts on “ASP.Net MVC Entity Framework Error – More than one context type was found in the assembly ‘ProjectName’.

Leave a Reply