Will look somethng like
appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-database;Trusted_Connection=True;MultipleActiveResultSets=true",
"BlogsConnection": "Server=(localdb)\\mssqllocaldb;Database=BlogsDb"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
BlogsDbContext.json
public class BlogsDbContext : DbContext
{
public DbSet Blogs { get; set; }
public DbSet Posts { get; set; }
public BlogsDbContext(DbContextOptions options)
: base(options)
{
}
}
Startup.json
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.AddEntityFramework()
.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("BlogsConnection")));
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
});
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
AdminController.json
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-database;Trusted_Connection=True;MultipleActiveResultSets=true",
"BlogsConnection": "Server=(localdb)\\mssqllocaldb;Database=BlogsDb"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
Some Debugging usefull steps
Steps for adding more DbContexts to an application:
Steps for adding more DbContexts to an application:
- Create a DbContext Class
- Create a Connection string DbContext in appsettings.json
- Add the DbContext to configured services in Startup.cs
- Setup the DbContext in the controllers that will query it.
- Open the package manager and run the 2 lines below. (if “-Context” doesn’t work try “–context”
- Run your program and let EntityFrameworkCore take care of the rest.
On Windows ( In Package Management Console you can run )
Add-Migration InitialCreate -Context MyContext
Update-Database -Context MyContex
On Linux ( VScode )
dotnet ef migrations add InitialCreate // TimeStamp_InitialCreate.Designer.cs
OR dotnet ef migrations add InitialCreate --context MyContext
dotnet ef database update
OR dotnet ef database update --context MyContext
Leave A Comment?