11

我正在构建一个 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= .....") ;

4

3 回答 3

6

至少对于 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

于 2017-07-10T13:19:47.277 回答
3

在您的内部,您appsettings.json将创建以下内容:

{
     "Database" : {
          "ConnectionString" : "..."
      }
}

然后在您的内部,您ConfigureServices将执行以下操作:

services.AddSingleton(_ => Configuration);

这将基本上填充该IConfigurationRoot属性。您可以在任何地方注入,并通过执行以下操作访问连接字符串:

private readonly IConfigurationRoot configuration;
private IDbConnection dbConnection { get; }

public Example(IConfigurationRoot configuration)
{
     this.Configuration = configuration;
     dbConnection = new SqlConnection(this.configuration.GetConnectionString("..."));
}

我的结构有点奇怪,您实际上只需将其传递ConnectionString给另一个类或注入方法,但这为您演示。但我相信 Entity Framework 7 有一个工厂可以直接接受连接字符串。希望这可以帮助你。

在实体框架中,您的内部应该是这样的ConfigureServices

services.AddSingleton<dbContext>(_ => new dbContext(Configuration.GetConnectionString("...")));
public class dbContext : DbContext
{
     public dbContext(string dbConnection) : base(dbConnection)
     {

     }
}

一些额外的文档

于 2016-12-15T17:03:47.623 回答
1

对于EntityFrameworkCore 2.1.4,您的连接字符串应该是这样的appsettings.json

  "ConnectionStrings": {
    "Connection1": "....",
    "Connection2": "..."
  },

将以下行添加到ConfigureServices方法中Startup.cs

 services.AddSingleton(provider => Configuration);

在这几行之后,

 services.AddDbContext<MyContextContext>
            (options => options.UseSqlServer(Configuration.GetConnectionString("Connection1")));
 services.AddScoped<DbContext, MyContext>();

并且您的数据库上下文类应修改如下。

public partial class MyContext : DbContext
    {
        private readonly IConfiguration _configuration;
        private IDbConnection DbConnection { get; }

        public MyContext(DbContextOptions<MyContext> options, IConfiguration configuration)
            : base(options)
        {
            this._configuration = configuration;
            DbConnection = new SqlConnection(this._configuration.GetConnectionString("Connection1"));
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(DbConnection.ToString());
            }
        }
    }
于 2018-10-29T06:57:31.257 回答