2017-04-04 278 views
0

这里我设置从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如何从Asp.netcore Access数据库通过使用Entityfrmework

这是我的数据库连接

{ 
    "connectionStrings": { 
    "DefaultConnection": "Server=MD;Database=Md;userid=sa;password=123;Trusted_Connection=True;MultipleActiveResultSets=true;" 
    } 

startUp.cs

public void ConfigureServices(IServiceCollection services) 
     { 
      services.AddDbContext<StudentContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 
      services.AddMvc(); 
     } 

DbContext.cs

public class StudentContext:DbContext 
    { 
     public StudentContext(DbContextOptions<StudentContext> options) : base(options) { } 
     public StudentContext() { } 

     public DbSet<StudentMaster> StudentMaster { get; set; } 
    } 

回答

0

参考在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(); 

    } 

然后确保你得到intended variable的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()); 

    } 

}

+0

appsetting.json,因为我在这个文件ü可以PLZ编写符合我这是R8或错误配置 –