我的解决方案中有两个项目,其中一个是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方法中使用两个连接字符串?
appsettings.json文件中没有Data:DefaultConnection
元素。相反,尝试使用Configuration["ConnectionStrings:DefaultConnection"]
。这也适用于LocalConnection
。
更容易使用GetConnectionString()
扩展方法。例如:
Configuration.GetConnectionString("DefaultConnection")