如何使用ConfigurationManager从应用程序设置中获取连接字符串



我创建了一个asp.net核心web api项目,该项目包含Microsoft.EntityFrameworkCore.SQL Server、Microsoft.EntityFrameworks core.Tools和System.Configuration.ConfigurationManager。我运行了脚手架命令Scaffold-DbContext "Data Source=DEX-LEP3LOXH0M5\SQLEXPRESS;Initial Catalog=LibraryStore;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

在从脚手架创建的Context.cs文件中,cmd创建了以下方法:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
optionsBuilder.UseSqlServer("Data Source=DEX-LEP3LOXH0M5\SQLEXPRESS;Initial Catalog=LibraryStore;Integrated Security=True");

}
}

当我运行到控制器的路由路径时,它运行得很好,我能够从DB中看到记录。但在#warning消息上,它提供了一个我关注的链接。在我的appsettings.json文件中,我通过以下操作添加了ConnectionStrings

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Default": "Data Source=DEX-LEP3LOXH0M5\SQLEXPRESS;Initial Catalog=LibraryStore;Integrated Security=True"
}
}

然后我的下一步是在startup.cs:中的ConfigureServices中添加代码

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "LibraryWebAPI", Version = "v1" });
});
services.AddDbContext<LibraryStoreContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Default")));
}

则它表示要更改所创建的Context.cs文件中的CCD_ 5。

我做了以下事情:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{

optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
}
}

但随后它在线路optionsBuilder:上产生错误消息

System.Configuration.ConnectionStringSettingsCollectionthis[string].get返回null。

如果在appsettings中按照链接将连接添加到连接字符串之前,相同的连接字符串工作,那么它返回null是有原因的吗?


包括我的控制器:

[HttpGet]
[Route("GetAllDetails")]
public IEnumerable<LibraryInfo> GetDetails()
{
using (var context = new LibraryStoreContext())
{
// get all library details
return context.LibraryDetails.ToList();
}
}

我确实找到了一种更舒适的方法来维护生成迁移,在这种方法中,您不必从web项目中运行命令。

DbContext

internal class ContosoContext : DbContext
{
private readonly IConfiguration configuration;
public ContosoContext(IConfiguration configuration)
{
this.configuration = configuration;
}
public ContosoContext()
{
this.configuration = null;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
if (configuration == null)
{
// Only used when generating migrations
// Contoso.Data = name of the project where your migrations should reside
var migrationsConnectionString = @"Server=(localdb)mssqllocaldb;Database=Contoso;Trusted_Connection=True;ConnectRetryCount=0";
optionsBuilder.UseSqlServer(migrationsConnectionString, options => options.MigrationsAssembly("Contoso.Data"));
}
else
{
optionsBuilder.UseSqlServer(configuration.GetConnectionString("Contoso"));
}
}
}

DbContext的注册

services.AddDbContext<ContosoContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("Contoso"));
});
  • 运行应用程序(web项目)时,将调用带有参数的构造函数
  • Contoso.Data文件夹(dotnet ef migrations add myawesomemigration)生成迁移时,将调用无参数构造函数

这减少了在生成数据库迁移过程中过度指定参数的需要:

dotnet ef migrations add AddIdentity

.Net Core应用程序使用appsettings.json而不是web.config文件。

由于.Net Core应用程序是自托管的,几乎可以在任何平台上运行,因此它们不再需要托管在IIS上。默认情况下,.Net Core应用程序设置以Json格式(appsettings.Json)存储,而.Net Framework应用程序配置则以XML格式存储在web.config文件中这就是为什么在使用ConfigurationManager时,它不应该与您的appsettings.json一起使用

根据您发送的guid,他们说要在protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)中进行更改

但这是说不上.net核心应用

最新更新