![](/img/trans.png)
[英]how to get connection string in .net core to Azure SQL without Entity Framework?
[英].NET Framework and Entity Framework Core: How can I get hold of the connection string
我已經在 .NET Framework 4.7.2 類庫中安裝了 EF Core。 這只是一個包含某些特定功能的項目,而不是解決方案中的StartUp
項目。 然后,帶有 EF Core 的項目被主項目引用,其中web.config
和 IoC 設置存在。 解決方案是針對網站。
根據此頁面,支持 .NET Framework 4.7.2。
問題在於注入或以其他方式獲取連接字符串,或者可能是任何其他配置/應用設置值。
假設這是我的DbContext
類:
public class PersonContext : DbContext
{
public DbSet<Person> Persons { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
if (ConfigurationManager.AppSettings["ConnectionString"] == null)
{
throw new Exception("Hey!");
}
optionsBuilder.UseSqlServer(ConnectionString);
}
}
}
當我運行Add-Migration
或Remove-Migration
等命令時, AppSettings["ConnectionString"]
為空,並且拋出異常。
我認為這是由於應用程序處於“設計模式”,並且尚未讀取web.config
。 我需要能夠為不同的環境指定不同的連接字符串。
關於如何從<appSettings>
或<connectionStrings>
獲取連接字符串的任何想法?
編輯:我還想補充一點,該解決方案將 Structuremap 用於 IoC,並且在包管理器控制台中運行遷移命令時,我無法注入 DbContext。
嘗試這個:
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.