Entity Framework Connection String不保留密碼的方法
阿新 • • 發佈:2018-05-22
play database inf -i actor display 密碼 ger one
添加Entity Data Model的時候,到最後一步,有兩個radio box:
如果選擇include sensitive data,雖然很方便,但是在web.config或者app.config文件的數據庫鏈接字符串就會保留數據庫的登陸密碼。
如果選擇不保留敏感信息,那麽數據庫連接字符串就會不保留密碼,而我們需要在代碼裏面增加相關的信息。
舉例子:如果創建的一個Entity Data Model名為ContactsEntities,那麽,我們需要修改ContactsEntities類的構造函數:
public ContactsEntities() :base("name=ContactsEntities") { var originalConnectionString = ConfigurationManager.ConnectionStrings["ContactsEntities"].ConnectionString; var entityBuilder = new EntityConnectionStringBuilder(originalConnectionString); var factory = DbProviderFactories.GetFactory(entityBuilder.Provider);var providerBuilder = factory.CreateConnectionStringBuilder(); providerBuilder.ConnectionString = entityBuilder.ProviderConnectionString; providerBuilder.Add("Password", "Password2018"); entityBuilder.ProviderConnectionString = providerBuilder.ToString();this.Database.Connection.ConnectionString = entityBuilder.ProviderConnectionString; }
程序運行後,就會讀取配置文件的名為ContactsEntities的connectionStrings,獲取data source,user id等信息。然後會補上缺失的password信息,成功連接上數據庫。
參考文章:
EF下使用自定義的connectionString避免數據庫密碼泄露
How to in-code supply the password to a connection string in an ADO.Net Entity Data Model
Entity Framework Connection String不保留密碼的方法