我遵循了this article,我尝试通过在Startup.cs中进行配置来从appsettings.json获取连接字符串,但它不起作用,并抛出错误InvalidOperationException: No database provider has been configured for this DbContext.
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<StudentManagementContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("StudentDatabase")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"StudentDatabase": "Data Source=localhost;Initial Catalog=StudentManagement;persist security info=True;user id=sa;password=test@123"
}
}
StudentManagementContext.cs
public partial class StudentManagementContext : DbContext
{
public StudentManagementContext()
{
}
public StudentManagementContext(DbContextOptions<StudentManagementContext> options)
: base(options)
{
}
public virtual DbSet<Student> Student { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=StudentManagement;persist security info=True;user id=sa;password=test@123");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.6-servicing-10079");
modelBuilder.Entity<Student>(entity =>
{
entity.Property(e => e.StudentName)
.IsRequired()
.HasMaxLength(100);
});
}
}
答案 0 :(得分:1)
扩展配置方法如下:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("StudentDatabase");
optionsBuilder.UseSqlServer(connectionString);
}
}