我有一個問題,當我試圖訪問我PartsDbContext現場我得到以下錯誤:實體框架核心使用多個DbContexts
System.Data.SqlClient.SqlException: 'Invalid object name 'fieldName''
看來,這是因爲我想使我的PartsDbContext使用與我的ApplicationDbContext相同的數據庫,它與Identity一起使用。我需要知道如何設置第二個dbcontext以與使用/創建不同數據庫的EF內核一起工作。
我試圖創建第二個連接字符串,但讓我這個錯誤:
System.Data.SqlClient.SqlException: 'Cannot open database "PartsDb" requested by the login. The login failed. Login failed for user 'DESKTOP-4VPU567\higle'.'
這裏是我的代碼:
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);
}
}
線var model = _context.Towers.ToList();
是其中所述錯誤被顯示出來。
再次。我想設置我的PartsDbContext以使用EF-Core將自動創建數據庫的方式與Entity Framework Core一起工作。
你能TY更換'「PartsConnection」:「服務器=(的LocalDB )\\ mssqllocaldb; Database = PartsDb「'with'」PartsConnection「:」Server =(localdb)\\ mssqllocaldb; Database = PartsDb; Trusted_Connection = True「'? –