Home

Dynamic ConnectionString Credentials for DbContext Instance?

I have a DbContext class that I've been using successfully from LINQPad so long as I specify either integrated auth or an explicit user id and password in the connection string. In order to avoid hard-coding the credentials in scenarios where I have to use a SQL login, I have some code in the parameterless constructor of my DbContext which retrieves the ConnectionString (using this.Database.Connection.ConnectionString) and inspects it to see if it has explicit credentials or Integrated Auth specified. If not, I retrieve the credentials to use from a secure store and then I append User Id=whatever;Password=whatever; to the end of the ConnectionString and then drop out of the constructor.

This works fine if I'm using my assembly from something other than LINQPad but with LINQPad I get the commonly-seen-via-Google error "This operation requires a connection to the 'master' database. Unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. Supply an unopened connection." I tried the usual trick of setting Persist Security Info to true and Trusted_Connection to false to no avail.

I suspect the problem may have to do with the number of times and/or the order in which the context connection is instantiated (through reflection as I understand it) in the LINQPad app domain.

As a final thought, I also noticed in the stack trace that it's blowing up while trying to run the database initializer, even though I have it set to disable database initialization in the entityFramework/contexts section of the custom config file but that seems to be ignored and the default CreateDbIfNotExists initializer is running anyway. I even tried adding that to the LINQPad.exe.config file itself in case this was some kind of "bootstrapping" problem.

Can you see any obvious problem with what I'm trying to do? Is it just a chicken-and-egg problem of some kind?

Thank you in advance for any suggestions you can offer.

Comments

  • Welp, the whole issue was solved by adding this at the top of the code:
    System.Data.Entity.Database.SetInitializer<UserQuery>(null);
    
    I had tried to do it through config but it looks like because of the way the UserQuery class is built into a dynamically generated assembly whose name varies every time, there isn't a way (at least that I could think of) to specify it other than through code.
Sign In or Register to comment.