微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有EntityFramework Core的Appsettings中的NET Core 3.1连接字符串

如何解决带有EntityFramework Core的Appsettings中的NET Core 3.1连接字符串

我有一个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;..."
  },}
,

您的上下文可能不应该知道其配置方式,甚至不知道正在使用哪个数据库引擎。在asp.net核心项目中,这应该是Startup类的工作。例如;

    public class Startup
    {
        private IConfiguration Configuration;
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<MyDbContext>(o =>
            {
                o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),...);
            });
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host
            .CreateDefaultBuilder(args)
            ...
            .ConfigureAppConfiguration((ctx,config) => {
                    config
                        .SetBasePath(ctx.HostingEnvironment.ContentRootPath)
                        .AddJsonFile("appsettings.json",true,true)
                        .AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json",optional: true,reloadOnChange: true);
                })
            ... ;

EF Core命令行工具将找到您的CreateHostBuilder方法并调用它以发现您的数据库上下文及其配置方式。例如,在创建迁移脚本时。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。