Drake Drake - 20 days ago 5
ASP.NET (C#) Question

Entity Framework and Connection string with custom Encryption

I am using an Oracle DB with EF 6 code first.
And did custom encryption on connection string.
Connection string stores in separate config file "connstring.config": There is a clear connection string without encryption

<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="MyConnString" connectionString="Data Source=MySource;User ID=UserID;Password=Password;PERSIST SECURITY INFO=True;"
providerName="Oracle.ManagedDataAccess.Client" />
</connectionStrings>


Data sources in web.config file.

MyDbcontext:

public static string GetConnectionString()
{
string encodedConnStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString.ToString();
string result = Crypto.Decrypt(encodedConnStr);
return result;
}
public MyDbContext() : base(GetConnectionString()){}


And when I run application I am getting Server Error : Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.

How can I solve this?

Answer

Because you are passing the connection string directly to the DbContext constructor you need to provide it with a database provider otherwise it does not know what database type it is creating connections for. The easiest thing to do is to alter the connection string, you can do this post encryption in your static method or in your encrypted connection string. Based on your connection above I believe oracle.manageddataaccess.client is the correct provider but test it and see.

Provider=oracle.manageddataaccess.client;Data Source=MySource;User ID=UserID;Password=Password;PERSIST SECURITY INFO=True

You can also try thing according to this other answer I found on SO: How to set manually an Oracle Connection String in a DbContext

class MyDbContext: DbContext
{
    public MyDbContext() : base(new OracleConnection(GetConnectionString()){}
    ...
}

If you are still experiencing problems update your question with just the relevant parts: that you cannot instantiate a DbContext instance when you manually provide a connection string. As it is written now it is very easy to make the assumption that your issue was with the encryption/decryption but these are irrelevant to the actual problem.