c# - NET Core 3.1 应用程序设置中的连接字符串与 EntityFramework Core
问题描述
我有一个 WEB API 应用程序,并且模板(或 EF Core)已经在上下文所在的文件中设置了连接字符串。我想从那里删除它并将其放入 appsettings 文件中并在 DbContext 的方法 OnConfiguring() 中读取它。
public partial class ReportingContext : DbContext
{
public MyAppContext() {}
public MyAppContext(DbContextOptions<MyAppContext> options) : base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("my-connection-string", x => x.UseNetTopologySuite());
//I want to remove the connection string from the above line, by reading from the appsettings file
}
}
}
如您所见,它位于上下文的 OnConfiguring 方法中。例如,如果我尝试放在外部,例如在启动时,应用程序将不再工作,因为它需要在 OnConfiguring 中指定的连接字符串,因为模型中的逻辑以下列方式实例化上下文:
public partial class SomeClassOfMine
{
public static List<BusinessLogic.Dto.NearbyMarkets> GetNearbyMarkets(int adm0code, double lat, double lng)
{
var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
var location = geometryFactory.CreatePoint(new Coordinate(lng, lat));
using (var db = new Models.Context.MyAppContext())
{
//as you can see above, the context is instantiated without passing parameters, and I don't want to pass the connection string in all the new context instance!
...query and logic execution here
}
}
}
我尝试在 OnConfiguring 中使用 Configuration.GetConnectionString("MyDatabaseDEV"),但它说 Microsoft.Extensions.Configuration 没有 GetConnectionString 方法
解决方案
如何在 Context 类中注入 IConfiguration?
获取DbContext中appsetting.json中的连接字符串,请参考写法:
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
}
}
}
请确保您在以下位置注册服务startup.cs
:
services.AddDbContext<MyDbContext>();
appsetting.json:
{
//...
"ConnectionStrings": {
"DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;..."
},
}
推荐阅读
- python - SymPy中眼睛和身份的区别
- amazon-web-services - 在 user_data 配置文件中实现“for 循环”
- image - 在qml中拖动矩形的角时如何制作可调整大小的矩形
- c# - Winforms - Webbrowser 将 onClick 事件添加到表格单元格
- javascript - 带有 Konva.js 的上下文菜单
- apache-spark - Spark:在不更改列的可为空属性的情况下转换小数
- php - “大于”和“小于”运算符在查询中不起作用
- hashicorp-vault - Vault:如何获取 kv 机密列表
- node.js - 使用 Jenkins 构建 Node.js 和 React.js
- django - django如何修复兼容性?