添加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