两个连接ASP.NET Core,EF core,ArgumentNullException错误

问题描述 投票:-3回答:1

我的解决方案中有两个项目,其中一个是Identity注册,另一个是ASP.NET Core MVC项目。我已经在appsettings.json中为official documentation for connection strings添加了另一个Identity连接。但是我在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方法中使用两个连接字符串?

c# json asp.net-core connection-string
1个回答
1
投票

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

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

Configuration.GetConnectionString("DefaultConnection")
© www.soinside.com 2019 - 2024. All rights reserved.