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.