首页 > 解决方案 > 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 方法

标签: c#asp.net-coreasp.net-web-apientity-framework-core

解决方案


如何在 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;..."
  }, 
}

推荐阅读