c# - 如何从 ASP.Net Core 中的 SqlServerDBContextOptionsExtensions 获取连接字符串

标签 c# asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-middleware

我正在构建一个 ASP.Net Core API,但我无法找到从 DBContextOptions 获取连接字符串的方法。

我的 startup.cs 中有 DBContext,如下所示;

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddEntityFrameworkSqlServer()
        .AddDbContext<MainContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MainConnection")));

    services.AddMvc()
       .AddJsonOptions(opt =>
        {
            opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });
}

在我的 Context 类中,我有以下构造函数;

public MainContext(DbContextOptions<MainContext> options) : base(options)
{

}

但它不起作用,除非我在 DBContext 类 OnConfiguring 方法中添加一个实际的连接字符串,如下所示;

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    //TODO Move connection string to a secure location
    optionsBuilder.UseSqlServer(@"Server= .....");

}

当我调试并检查 Configuration.GetConnectionString("MainConnection") 中的值时,我可以看到 Startup.cs 从 appsettings.json 文件中获取正确的连接字符串。

我认为通过 DI 将选项传递到 DbContext 类会传递连接字符串,但 DbContect 类不起作用,除非我在 OnConfiguring 方法中有 optionBuilder.UseSqlServer()。

我找到了这篇 SO 帖子 https://stackoverflow.com/questions/33532599/asp-net-5-multiple-dbcontext-problems ,讨论使用以下代码从选项属性中提取连接字符串

public ResourceDbContext(DbContextOptions options) : base(options)
{
    _connectionString = ((SqlServerOptionsExtension)options.Extensions.First()).ConnectionString;
}


protected override void OnConfiguring(DbContextOptionsBuilder options)
{
    options.UseSqlServer(_connectionString);
}  

但是当我尝试使用它时,我发现options.Extensions中不再有First()方法

所以,我的第一个问题是......

为什么无需在 OnConfiguring 方法中添加连接字符串,DBContext 类就无法工作

我的第二个问题是......

如果 OnCONfiguring 方法中需要连接字符串,我如何从 DbContextOptions 选项对象中获取它而不是必须在 OnConfiguring 方法中显式提供它 --> optionsBuilder.UseSqlServer(@"Server= ... ”);

最佳答案

至少对于 EF Core 1.1,您需要使用 FindExtension<SqlServerOptionsExtension>()

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;

namespace MyNamespace
{
    public class MyContext : DbContext
    {
        public MyContext(DbContextOptions<MyContext> options) : base(options)
        {
            var sqlServerOptionsExtension = 
                   options.FindExtension<SqlServerOptionsExtension>();
            if(sqlServerOptionsExtension != null)
            {
                string connectionString = sqlServerOptionsExtension.ConnectionString;
            }
        }
    }
}

如果您使用 opt.UseInMemoryDatabase(),则可以进行空检查在你的Startup.cs

关于c# - 如何从 ASP.Net Core 中的 SqlServerDBContextOptionsExtensions 获取连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169388/

相关文章:

c# - 如何使用泛型为多种数据类型创建通用的加法方法?

c# - 如何更改 ListView 标题的前景色? C# 窗体应用程序

c# - 如何在 ConfigureServices 中获取 Development/Staging/production Hosting Environment

c# - MVC ICollection<IFormFile> ValidationState 始终设置为 Skipped

c# - Azure Linux ASP 上运行的 .net core 与 Azure SQL 数据库之间的连接池问题

c# - MVC6,如果用户从 View 中提交空的十进制/整数值,服务器端模型验证将显示错误消息

c# - 如何在 LINQ 查询期间将 XML 属性(字符串)解析为(int)

C# 索引不在上下文中

asp.net-core - .NET Core 2 和 Font Awesome。如何在构建时将 webfonts 从 node_modules 复制到 wwwroot?

azure - 在 ASP.NET Core 3.0 MVC 项目中,我到底如何使用 ilogger 记录应用程序洞察?