【问题标题】:Two connections ASP.NET Core, EF core, ArgumentNullException error两个连接ASP.NET Core、EF core、ArgumentNullException错误
【发布时间】:2019-04-10 11:51:03
【问题描述】:

我的解决方案中有两个项目,一个是身份注册,另一个是 ASP.NET Core MVC 项目。我在 appsettings.json 中为 official documentation for connection strings 添加了另一个身份连接。但是我在 ConfigureServices 方法中的 Microsoft.EntityFrameworkCore.SqlServer.dll 中出现异常 System.ArgumentNullException'。

我更改的 appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=employeedb;Trusted_Connection=True;MultipleActiveResultSets=true",
    "LocalConnection": "Server=(localdb)\\mssqllocaldb;Database=employeedb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

ConfigureServices 方法

public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddEntityFrameworkSqlServer()
            .AddDbContext<EmployeeContext>(options => {
                options.UseSqlServer(Configuration["Data:DefaultConnection"]);
            })
        .AddDbContext<ApplicationContext>(options => {
            options.UseSqlServer(Configuration["Data:LocalConnection"]); 
        });

        var mappingConfig = new MapperConfiguration(mc =>
        {
            mc.AddProfile(new MappingProfile());
        });
        IMapper mapper = mappingConfig.CreateMapper();
        services.AddSingleton(mapper);

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddIdentity<User, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationContext>();
        services.AddScoped<IEmployeeService, EmployeeService>();
    }

ConfigureServices 方法中的异常

如何在 ConfigureServices 方法中获得两个连接字符串?

【问题讨论】:

  • 不要发布错误信息的图片。将其作为文本发布(连同堆栈跟踪)。
  • 可能Configuration["Data:DefaultConnection"] 为空。另外,Configuration 到底是什么?
  • 它不重复我还有一个问题

标签: c# json asp.net-core connection-string


【解决方案1】:

您的 appsettings.json 文件中没有 Data:DefaultConnection 元素。相反,请尝试使用Configuration["ConnectionStrings:DefaultConnection"]。这也适用于LocalConnection

使用GetConnectionString() 扩展方法可能更容易。例如:

Configuration.GetConnectionString("DefaultConnection")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多