Entity Framework Core Using Multiple DbContexts

I had a problem: when I try to access a field in my PartDbContext, I get the following error:

System.Data.SqlClient.SqlException: 'Invalid object name' fieldName ''

This seems to be due to the fact that I'm trying to get my PartDbContext to use the same database as my ApplicationDbContext, which is used with Identity. I need to know how to configure 2nd dbcontext to work with an EF core that uses / creates another database.

I tried to create a second connection string, but I got this error:

System.Data.SqlClient.SqlException: "Cannot open the PartsDb database requested at login. Login failed. Login failed for user 'DESKTOP-4VPU567 \ higle.'

Here is my code:

appsettings.json

"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-PrecisionCustomPC-b14db89e-86ad-4855-a17f-ac64a04339aa;Trusted_Connection=True;MultipleActiveResultSets=true", "PartsConnection": "Server=(localdb)\\mssqllocaldb;Database=PartsDb" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } 

PartsDbContext.cs

 public class PartsDbContext : DbContext { public DbSet<PartsViewModels.Tower> Towers { get; set; } public DbSet<PartsViewModels.Motherboard> Motherboards { get; set; } public PartsDbContext(DbContextOptions<PartsDbContext> options) : base(options) { } } 

Startup.cs

 public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddEntityFramework() .AddDbContext<PartsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PartsConnection"))); services.AddMvc(); services.AddAuthorization(options => { options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin")); }); // Add application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); } 

Admincontroller.cs

 [Authorize(Policy = "RequireAdminRole")] public class AdminController : Controller { private readonly PartsDbContext _context; public AdminController(PartsDbContext context) { _context = context; } public IActionResult Index() { return View(); } public IActionResult Towers() { var model = _context.Towers.ToList(); return View(model); } } 

In the line var model = _context.Towers.ToList(); an error.

Again. I want to configure my PartDbContext to work with the Entity Framework core so that EF-Core will automatically create the database.

+13
source share
2 answers

I get it. This was mainly due to the fact that I accidentally deleted the database that Identity used, and I needed to figure out how to get it back.

There seems to be nothing wrong with my connection string as it is. I just needed to go into the package manager and enter these commands in the following order:

  • Add-Migration init -Context PartsDbContext
  • Update-Database -Context PartsDbContext

I found this because it was what I had to do to start my ApplicationDbContext 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 to add additional DbContexts are as follows:

  • Create DbContext Class
  • Create a Connection string for this DbContext in appsettings.json
  • Add DbContext to your configured services in Startup.cs
  • Install DbContext in the controllers that will use it.
  • Open the package manager and run 2 lines above. (if "-Context" does not work, try "--context"
  • Run the program and let EntityFrameworkCore take care of the rest.
+14
source

Here, the article describes how to work with several different DBContexts and one database. And code examples. Entity Framework Core with multiple database contexts, schemas, and projects

0
source

All Articles