Gio*_*iox 0 c# asp.net-web-api entity-framework-core asp.net-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
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它位于上下文的 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试在 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"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
请确保您在以下位置注册该服务startup.cs:
services.AddDbContext<MyDbContext>();
Run Code Online (Sandbox Code Playgroud)
应用程序设置.json:
{
//...
"ConnectionStrings": {
"DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;..."
},
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3227 次 |
| 最近记录: |