【问题标题】:The name "Configuration" does not exist in the current context当前上下文中不存在名称“配置”
【发布时间】:2021-02-07 07:48:04
【问题描述】:

尝试在 startup.cs 中注册数据库上下文时

public void ConfigureServices(IServiceCollection services)
{
        services.AddMvc(option => option.EnableEndpointRouting = false);
        services.AddDbContext<PostDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("PostDbContext")));
 }

我收到错误

The name "Configuration" does not exist in the current context.

所有代码示例均取自微软官方文档。 教程 -> MVC -> 入门 -> 添加模型。 ASP.NET Core 版本:3.1 如何解决?

【问题讨论】:

  • 你是在appsettings.json文件中设置的吗?请参阅标题 Sdd 数据库连接字符串下的 here
  • 是的,我在 appsetting.json 中添加了"ConnectionStrings": { "PostContext": "Server=(localdb)\\mssqllocaldb;Database=PostDbContext-1;Trusted_Connection=True;MultipleActiveResultSets=true" }
  • 上面的代码中有PostDbContext,连接字符串中有PostContext。让它们都一样!
  • 如果您在问题中显示该配置部分会很有帮助。
  • 这行不通。

标签: asp.net asp.net-mvc database asp.net-core


【解决方案1】:

我还没有定义配置。

public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

【讨论】:

    【解决方案2】:

    出现这个问题是因为你没有定义像这样的 IConfiguration 接口实例的 Configuration-

    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration)
    {
       Configuration = configuration;
    }
     
    

    这里的配置对于定义哪些检查配置细节很重要。 对于 Ex.-Configuration.GetConnectionString("Your Connection String") 检查 appsettings.json 文件中的连接字符串以获取或设置数据库中的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 2014-04-22
      • 2017-06-17
      • 2015-09-11
      • 1970-01-01
      • 2020-12-05
      相关资源
      最近更新 更多