簡體   English   中英

.NET Framework 和 Entity Framework Core:如何獲取連接字符串

[英].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-MigrationRemove-Migration等命令時, AppSettings["ConnectionString"]為空,並且拋出異常。

我認為這是由於應用程序處於“設計模式”,並且尚未讀取web.config 我需要能夠為不同的環境指定不同的連接字符串。

關於如何從<appSettings><connectionStrings>獲取連接字符串的任何想法?

編輯:我還想補充一點,該解決方案將 Structuremap 用於 IoC,並且在包管理器控制台中運行遷移命令時,我無法注入 DbContext。

嘗試這個:

var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM