[英]How can I get connectionstring from appsetting using ConfigurationManager?
我创建了一个 asp.net 核心 web api 项目,其中包含 Microsoft.EntityFrameworkCore.SqlServer、Microsoft.EntityFrameworkCore.Tools 和 System.Configuration.ConfigurationManager。 我运行了脚手架命令Scaffold-DbContext "Data Source=DEX-LEP3LOXH0M5\\SQLEXPRESS;Initial Catalog=LibraryStore;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
。
在从脚手架 cmd 创建的 Context.cs 文件中创建了这个方法:
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");
}
}
当我运行到 controller 的路由路径时,它运行良好,我能够从数据库中看到记录。 但在那条#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 文件中的OnConfiguring()
。
我做了以下事情:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
}
}
但随后它会在optionsBuilder
行生成错误消息:
System.Configuration.ConnectionStringSettingsCollection.this[string].get 返回 null。
如果在按照链接将连接添加到 appsettings 中的 connectionstring 之前相同的连接字符串有效,它是否返回 null 是有原因的吗?
包括我的控制器:
[HttpGet]
[Route("GetAllDetails")]
public IEnumerable<LibraryInfo> GetDetails()
{
using (var context = new LibraryStoreContext())
{
// get all library details
return context.LibraryDetails.ToList();
}
}
我确实找到了一种更舒适的方式来维护生成的迁移,您不必从 web 项目运行命令。
数据库上下文
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"));
});
Contoso.Data
文件夹生成迁移时 ( do.net 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应用程序ConfigurationManager
以 XML 格式存储在 web.config 文件中
从您发送的 guid 中,他们说要在protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
中进行更改
但是据说.net内核上没有这个应用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.