连接字符串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.

WinForms & WPF 应用程序WinForms & WPF Applications

WinForms、WPF 和 ASP.NET 4 应用程序都有一个已尝试并经过测试的连接字符串模式。WinForms, WPF, and ASP.NET 4 applications have a tried and tested connection string pattern. 如果你使用的是 ASP.NET,则应将连接字符串添加到应用程序的 app.config 文件(web.config)中。The connection string should be added to your application's 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 the Secret Manager tool.

<?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 连接字符串上不需要此设置。The providerName setting is not required on EF Core connection strings stored in App.config because the database provider is configured via code.

然后,你可以在上下文的ConfigurationManager OnConfiguring方法中使用 API 来读取连接字符串。You can then read the connection string using the ConfigurationManager API in your context's OnConfiguring method. 可能需要添加对System.Configuration框架程序集的引用才能使用此 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.json 中存储的连接字符串。The 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>. 需要导入 Microsoft extension . 配置命名空间才能使用此扩展方法。You need to import the Microsoft.Extensions.Configuration namespace to use this extension method.

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