連接字串
大部分的資料庫提供者都需要某種形式的連接字串才能連線到資料庫。 有時候,此連接字串包含需要保護的敏感性資訊。 當您在環境之間移動應用程式時,您可能也需要變更連接字串,例如開發、測試和生產環境。
ASP.NET Core
在 ASP.NET Core組態系統非常有彈性,而且連接字串可以儲存在 appsettings.json
、環境變數、使用者密碼存放區或其他組態來源中。 如需詳細資訊,請參閱ASP.NET Core檔的設定一節。
例如,您可以使用 秘密管理員工具來 儲存資料庫密碼,然後在 Scaffolding 中使用只包含 的 Name=<database-alias>
連接字串。
dotnet user-secrets set ConnectionStrings:YourDatabaseAlias "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=YourDatabase"
dotnet ef dbcontext scaffold Name=ConnectionStrings:YourDatabaseAlias Microsoft.EntityFrameworkCore.SqlServer
或者,下列範例顯示儲存在 中的 appsettings.json
連接字串。
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
然後,內容通常會在 中 Startup.cs
設定為從組態讀取的連接字串。 請注意, GetConnectionString()
方法會尋找其索引鍵為 ConnectionStrings:<connection string name>
的組態值。 您必須匯入 Microsoft.Extensions.Configuration 命名空間,才能使用此擴充方法。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}
WinForms & WPF 應用程式
WinForms、WPF 和 ASP.NET 4 應用程式已嘗試並測試連接字串模式。 如果您使用 ASP.NET) ,則應將連接字串新增至應用程式的 App.config 檔案 (Web.config。 如果您的連接字串包含敏感性資訊,例如使用者名稱和密碼,您可以使用 受保護的組態來保護組態檔的內容。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="BloggingDatabase"
connectionString="Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" />
</connectionStrings>
</configuration>
秘訣
因為 providerName
資料庫提供者是透過程式碼設定,所以在儲存在 App.config 的 EF Core 連接字串上不需要此設定。
接著,您可以在內容的方法 OnConfiguring
中使用 ConfigurationManager
API 讀取連接字串。 您可能需要新增架構元件的參考 System.Configuration
,才能使用此 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)
UWP 應用程式中的連接字串通常是只指定本機檔案名的 SQLite 連線。 它們通常不包含敏感性資訊,而且不需要在部署應用程式時變更。 因此,這些連接字串通常會保留在程式碼中,如下所示。 如果您想要將它們移出程式碼,UWP 支援設定的概念,請參閱 UWP 檔的應用程式設定一節 以取得詳細資料。
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");
}
}