[英]Why do we use DependecyInjection instead of OnConfiguring Method in the DbContext?
[英]How do I set the OnConfiguring method in my DbContext without any hardcoded connection string?
我使用了多個關於如何設置 MySql 服務的示例,但幾乎在每個示例中(包括 Microsoft),它們都使用硬編碼的連接字符串。
這是我的啟動:
services.AddDbContext<DbContext>(options =>
{
options.UseMySql(configuration.GetConnectionString("DefaultConnection"),
mysqlOptions =>
{
mysqlOptions.ServerVersion(new ServerVersion(new Version(8, 0, 18)));
});
});
每當我嘗試Update-Database
我都會看到一個錯誤,告訴我沒有設置密碼
MySql.Data.MySqlClient.MySqlException (0x80004005): 用戶 'root'@'localhost' 的訪問被拒絕(使用密碼:YES)。
環顧四周后,我發現了一個名為OnConfiguring
的可覆蓋方法,但我想以動態方式設置連接字符串,因為如果我改變我的環境,我希望該字符串也改變。
這是我發現幾乎所有帶有硬編碼字符串的示例(例如https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core.html )
如果未配置,則需要初始化配置。
這可以通過覆蓋OnConfiguring
中的OnConfiguring
方法來DbContext
。
通過這種方式,您可以擁有將在應用程序運行時拉取的全局應用程序配置。 並在進行 Db 遷移時使用本地配置。
嘗試這個
public class YourContext: DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (options.IsConfigured == false)
options.UseMysql({YOUR_CONNECTION_STRING});
}
}
在配置文件中,您應該有一個 ConnectionStrings 指向您的數據庫和其他選項。
"ConnectionStrings": {
"DefaultConnection": "server=127.0.0.1;uid=root;pwd=12345;database=test"
},
當您使用 configuration.GetConnectionString 時,您正在從配置部分查找一個值。
在 startup.cs 試試這個
public class Startup
{
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
// This method gets called by the runtime. Use this method to add services to the
container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MainContext>(options =>
options.UseOracle(_config["CONNECTION_STRING"]));
}
}
並在您的 Context ctor 執行此操作
public MainContext(DbContextOptions<MainContext> options) : base(options) { }
根據評論,我認為您希望將 EF Core 相關類分離到不同的程序集。
在UseMySql
有一個配置MigrationsAssembly
的選項。 您可以在此處獲得更多詳細信息
這是 SQL Server 的偽代碼。
services.AddDbContext<EFCoreDemoContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
assembly => assembly.MigrationsAssembly(typeof(EFCoreDemoContext).Assembly.FullName));
});
我正在解決您問題的這一部分:
“環顧四周后,我發現了一個名為 OnConfiguring 的可覆蓋方法,但我想以動態方式設置連接字符串,因為如果我改變我的環境,我希望該字符串也改變。”
為了解決將連接字符串放入 DbContext 類中的 OnConfiguring 方法的問題,我只是像這樣將 IConfiguration 傳遞到 DbContext 構造函數中。
private readonly IConfiguration _config;
public CoreDbContext(IConfiguration config)
{
_config = config;
}
public CoreDbContext(DbContextOptions<CoreDbContext> options,
IConfiguration config) : base(options)
{
_config = config;
}
然后在 OnConfiguring 方法中,我從構造時注入的配置對象中提取連接字符串。 像這樣:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_config.GetConnectionString("YourKeyValueForConnStringInAppSettings.json"));
}
}
最后這里是我的環境/項目的詳細信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.