連接字串Connection Strings

大部分的資料庫提供者需要某種形式的連接字串以連接到資料庫。Most database providers require some form of connection string to connect to the database. 有時候此連接字串包含要保護的機密資訊。Sometimes this connection string contains sensitive information that needs to be protected. 此外,您可能也需要變更連接字串,當您在環境中,例如開發、 測試和生產環境之間移動您的應用程式。You may also need to change the connection string as you move your application between environments, such as development, testing, and production.

.NET framework 應用程式.NET Framework Applications

.NET framework 應用程式,例如 WinForms、 WPF、 主控台和 ASP.NET 4 中,已嘗試且測試過的連接字串模式。.NET Framework applications, such as WinForms, WPF, Console, and ASP.NET 4, have a tried and tested connection string pattern. 連接字串應該將您的應用程式的 App.config 檔 (Web.config 如果您使用 ASP.NET)。The connection string should be added to your applications App.config file (Web.config if you are using ASP.NET). 如果您的連接字串中包含機密資訊,例如使用者名稱和密碼,您可以保護的組態檔中使用內容受保護的組態If your connection string contains sensitive information, such as username and password, you can protect the contents of the configuration file using Protected Configuration.

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <connectionStrings>
    <add name="BloggingDatabase"
         connectionString="Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" />
  </connectionStrings>
</configuration>

提示

providerName EF Core 連接字串儲存在 App.config,因為資料庫提供者已透過程式碼不需要設定。The providerName setting is not required on EF Core connection strings stored in App.config because the database provider is configured via code.

您可以接著讀取連接字串使用ConfigurationManager在您的內容中的 APIOnConfiguring方法。You can then read the connection string using the ConfigurationManager API in your context's OnConfiguring method. 您可能需要將參考加入System.Configurationframework 組件,若要能夠使用此 API。You may need to add a reference to the System.Configuration framework assembly to be able to use this API.

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
    }
}

通用 Windows 平台 (UWP)Universal Windows Platform (UWP)

在 UWP 應用程式中的連接字串通常是只會指定本機檔案名稱的 SQLite 連線。Connection strings in a UWP application are typically a SQLite connection that just specifies a local filename. 它們通常不包含機密資訊,並不需要變更,因為應用程式的部署。They typically do not contain sensitive information, and do not need to be changed as an application is deployed. 因此,這些連接字串通常沒什麼問題可以留在程式碼,如下所示。As such, these connection strings are usually fine to be left in code, as shown below. 如果您想要移出程式碼 UWP 支援設定的概念,請參閱UWP 文件中的 [應用程式設定] 區段如需詳細資訊。If you wish to move them out of code then UWP supports the concept of settings, see the App Settings section of the UWP documentation for details.

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
            optionsBuilder.UseSqlite("Data Source=blogging.db");
    }
}

ASP.NET CoreASP.NET Core

在 ASP.NET Core 組態系統是非常有彈性,以及連接字串可以儲存在appsettings.json,環境變數、 使用者密碼存放區或另一個設定來源。In ASP.NET Core the configuration system is very flexible, and the connection string could be stored in appsettings.json, an environment variable, the user secret store, or another configuration source. 請參閱組態區段的 ASP.NET Core 文件如需詳細資訊。See the Configuration section of the ASP.NET Core documentation for more details. 下列範例顯示連接字串儲存在appsettings.jsonThe following example shows the connection string stored in appsettings.json.

{
  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}

內容通常會設定於Startup.cs正在從組態讀取的連接字串。The context is typically configured in Startup.cs with the connection string being read from configuration. 附註GetConnectionString()方法會尋找其索引鍵的組態值ConnectionStrings:<connection string name>Note the GetConnectionString() method looks for a configuration value whose key is ConnectionStrings:<connection string name>.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}