在这里,我设置了一些从 Anguar2 到数据库的 Db 连接,但是当我尝试访问数据库时,出现错误 Additional information: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the
这是我的数据库连接
{
"connectionStrings": {
"DefaultConnection": "Server=MD;Database=Md;userid=sa;password=123;Trusted_Connection=True;MultipleActiveResultSets=true;"
}
启动文件
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<StudentContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
数据库上下文
public class StudentContext:DbContext
{
public StudentContext(DbContextOptions<StudentContext> options) : base(options) { }
public StudentContext() { }
public DbSet<StudentMaster> StudentMaster { get; set; }
}
在 appsettings.json 中引用正确的变量(或任何文件名)
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
然后确保你得到了预期的变量(connectionStrings:DefaultConnection对于你的情况)
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<StudentContext>(option => option.UseSqlServer(Configuration.GetConnectionString("connectionStrings:DefaultConnection")));
services.AddMvc();
}
您还可以通过覆盖OnConfiguring
这样的方式直接在数据上下文上设置连接字符串
public class StudentContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("_connectionString_", _options => _options.EnableRetryOnFailure());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句