Entity Framework Core Using multiple DbContexts
I figured it out. This mostly came about because I accidentally deleted the database that Identity was using and I needed to figure out how to get it back.
Apparently there's nothing wrong with my connection string the way it is. I just needed to go into the package manager and type these commands in this order:
Add-Migration init -Context PartsDbContext
Update-Database -Context PartsDbContext
I found this out because that is what I had to do to get my ApplicationDbContext working again and it turns out that this step is done for you when you create a new MVC Core Web Application in Visual Studio using Individual User Authentication.
So basically the steps for adding more DbContexts is to:
- Create a DbContext Class
- Create a Connection string for that DbContext in appsettings.json
- Add the DbContext to your configured services in Startup.cs
- Setup the DbContext in the controllers that will use it.
- Open the package manager and run the 2 lines above. (if "-Context" doesn't work try "--context"
- Run your program and let EntityFrameworkCore take care of the rest.
In addition to the prior comments, you can use this way:
dotnet ef migrations add InitialCreate --context MyContext
dotnet ef database update --context MyContext
or
Add-Migration InitialCreate -Context MyContext
Update-Database -Context MyContext
First of all, thanks @Joe Higley answer this questions,I want to add more situation to help more people.
My situation is i'm trying to use EF-Identity and Area to create a admin panel, in my admin area own their own controller/models/views..., also contain a new DBcontext.
There is problems, if you try to context.Database.EnsureCreated();
to initialize DB there will show
System.Data.SqlClient.SqlException: 'Invalid object name 'fieldName''
Ref this link Migrations with Multiple Providers
We can use migrations and use --context to set which DbContext you want to run
In VScode you can run
dotnet ef migrations add InitialCreate --context BlogContext
dotnet ef database update
In Package Management Console you can run
Add-Migration InitialCreate -Context BlogContext
Update-Database