I have a database build with PostgreSQL, which I access through Entity Framework 6.
Until recently it ran smoothly through an app.config
connectionString:
<connectionStrings>
<add
name="fancyName"
connectionString="Host=localhost; user id=allCanSee; password=notSoSecret; database=notHidden"
providerName="Npgsql" />
</connectionStrings>
Our lead programmer is not happy about an open connectionString, since every computer we install the software on can read it. We therefore encrypted everything, and stored the encryption in the app.config
.
Now I have a new problem - I have accessed my database the following way:
public class VersionContext
{
public virtual DbSet<DatabaseNumber> DatabaseVersion { get; set; }
public VersionContext() : base("name=fancyName")
{
System.Data.Entity.Database.SetInitializer<DatabaseContext>(null);
}
}
But since my app.config
no longer contains the connectionString, I must tell the database where to look.
My current attempt is something like this:
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);
}
}
Then I'd access it as follow:
using (var context = new VersionContext())
{
var entry = context.DatabaseVersion.FirstOrDefault();
...
}
But this gives an exception from System.Data
saying Keyword not supported: 'provider'.
Removing provider
from the connectionString gives another exception: Keyword not supported: 'port'.
Removing port
from the connectionString gives a third exception from .Net SqlClient Data Provider
: Login failed for user 'secretSecret'.
So - how do I set my connectionString, if it's not set through the :base(connectionString)
property?