![](/img/trans.png)
[英]ERROR: System.InvalidOperationException: No database provider has been configured for this DbContext
[英]System.InvalidOperationException: when accessing DbContext
运行.Net Core应用程序时出现错误。 我开始访问DbContext并弹出
System.InvalidOperationException:'尚未为此DbContext配置数据库提供程序。 可以通过重写DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序。 如果使用AddDbContext,则还要确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给DbContext的基本构造函数。
我已经尝试修复它,但它仍然出现。
DbContext.cs
public class PartsDbContext : DbContext
{
public DbSet<Tower> Towers { get; set; }
public DbSet<Motherboard> Motherboards { get; set; }
public PartsDbContext(DbContextOptions<PartsDbContext> options)
: base(options)
{
}
}
Controller.cs
public class AdminController : Controller
{
private readonly PartsDbContext _context;
public AdminController(PartsDbContext context)
{
_context = context;
}
public IActionResult Index()
{
if (User.Identity.Name == null)
{
return RedirectToAction("Register", "Account");
}
return View();
}
public IActionResult Towers()
{
var model = _context.Towers.ToList();
return View(model);
}
public IActionResult Motherboards()
{
var model = _context.Motherboards.ToList();
return View(model);
}
}
错误显示在Towers()的这一行上
var model = _context.Towers.ToList();
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>();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
你能帮忙的话,我会很高兴。 我确定我做错了什么,但我相信我已经完成了错误提示的所有事情。
谢谢。
您当前的Startup.cs
文件已为一个数据库( ApplicationDBContext
)配置了数据库提供程序,但没有为您正在使用的数据库( PartsDbContext
)配置数据库提供ApplicationDBContext
。
因此,添加以下行:
services.AddDbContext<PartsDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
)
详细信息: https : //docs.microsoft.com/zh-cn/ef/core/miscellaneous/configuring-dbcontext#using-dbcontext-with-dependency-injection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.