【发布时间】:2016-12-25 09:43:43
【问题描述】:
我有一个使用 PostgreSQL 构建的数据库,我通过 Entity Framework 6 访问它。
直到最近它通过app.config connectionString 顺利运行:
<connectionStrings>
<add
name="fancyName"
connectionString="Host=localhost; user id=allCanSee; password=notSoSecret; database=notHidden"
providerName="Npgsql" />
</connectionStrings>
我们的首席程序员对打开的 connectionString 不满意,因为我们安装软件的每台计算机都可以读取它。因此我们加密了所有内容,并将加密存储在app.config。
现在我有一个新问题 - 我通过以下方式访问了我的数据库:
public class VersionContext
{
public virtual DbSet<DatabaseNumber> DatabaseVersion { get; set; }
public VersionContext() : base("name=fancyName")
{
System.Data.Entity.Database.SetInitializer<DatabaseContext>(null);
}
}
但是由于我的app.config 不再包含连接字符串,我必须告诉数据库在哪里查找。
我目前的尝试是这样的:
public static class VersionContextConnection
{
public static string GetConnectionString() //Accessable form everywhere
{
var providerName = "Npgsql";
var databaseName = decryptedName;
var userName = decryptedUserName;
var password = decryptedPassword;
var host = decryptedHostName
var port = 5432;
return $"Provider={providerName}; " + $"Server={host}; " + $"Port={port}; " +
$"User Id={userName}; " + $"Password={password}; " + $"Database={databaseName};";
}
}
public class VersionContext : DbContext
{
public virtual DbSet<DatabaseNumber> DatabaseVersion { get; set; }
public VersionContext() : base(VersionContextConnection.GetConnectionString())
{
System.Data.Entity.Database.SetInitializer<DatabaseContext>(null);
}
}
然后我将按如下方式访问它:
using (var context = new VersionContext())
{
var entry = context.DatabaseVersion.FirstOrDefault();
...
}
但这给了System.Data一个例外,说Keyword not supported: 'provider'.
从 connectionString 中删除 provider 会产生另一个异常:Keyword not supported: 'port'.
从 connectionString 中删除 port 会产生来自 .Net SqlClient Data Provider 的第三个异常:Login failed for user 'secretSecret'.
那么 - 如果我的 connectionString 不是通过 :base(connectionString) 属性设置的,我该如何设置它?
【问题讨论】:
-
在运行时设置呢?像这样的东西? stackoverflow.com/questions/360024/…
-
@Forlani 这是一个解决方案,但是密码和用户名会在运行时暴露出来......
标签: c# entity-framework postgresql connection-string