我有一个从ObjectContext继承的类:
public class MyObjectContext: ObjectContext {
[.....]
public MyObjectContext()
: base("name=MyObjectContext", "MyObjectContext")
{
ContextOptions.LazyLoadingEnabled = true;
}
public MyObjectContext(string connectionString)
: base(connectionString, "MyObjectContext")
{
ContextOptions.LazyLoadingEnabled = true;
}
[.....]
}
还有一个配置文件,我有一个用于db的连接字符串:
<connectionStrings>
<add name="RepoContext"
connectionString="metadata=res://*/Repo.RepoModel.csdl|res://*/Repo.RepoModel.ssdl|res://*/Repo.RepoModel.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\MyDb.sdf;Password=12345""
providerName="System.Data.EntityClient" />
</connectionStrings>
也就是说,我想从配置文件中完全删除密码,并在MyObjectContext
类内部动态加载它-密码。其余的connectionString必须保留在配置中。
我该怎么做?
我不想加密配置文件中的connectionString。
答案 0 :(得分:0)
您可以将基本构造函数与带有连接字符串的重载一起使用:
public MyObjectContext(string connectionString)
: base(connectionString)
{
ContextOptions.LazyLoadingEnabled = true;
}
并这样称呼它:
var cxt = new MyObjectContext(new EntityConnectionStringBuilder() {
Metadata= "metadata=res://*/Repo.RepoModel.csdl|res://*/Repo.RepoModel.ssdl|res://*/Repo.RepoModel.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\MyDb.sdf;Password=+"PASSWORD"+"",
Provider = "System.Data.EntityClient"
}.ConnectionString);
答案 1 :(得分:0)
像这样从MyObjectContext的构造函数调用函数
public MyObjectContext()
: base(GetConnectionString())
{
ContextOptions.LazyLoadingEnabled = true;
}
在您的函数中获取连接字符串
private static string GetConnectionString()
{
var connectStringValue = ConfigurationManager.ConnectionStrings["MyObjectContext"].ConnectionString;
var entityBuilder = new EntityConnectionStringBuilder(connectStringValue);
var factory = DbProviderFactories.GetFactory(entityBuilder.Provider);
var providerBuilder = factory.CreateConnectionStringBuilder();
if (providerBuilder == null)
return entityBuilder.ToString();
providerBuilder.ConnectionString = entityBuilder.ProviderConnectionString;
providerBuilder.Add("Password", "**yourpassword**");
entityBuilder.ProviderConnectionString = providerBuilder.ToString();
return entityBuilder.ToString();
}
希望这会有所帮助