简体   繁体   中英

Entity Framework - Database first - Intercepting DbContext

I am developing a Web API that uses Entity Framework 6. The Connection String for Entity Framework is encrypted with a company standard encryption. (sql server 2014) I can decrypt the connection string just fine, but I have not been able to figure out how to intercept DbContext to set the decrypted connection string. (Before the Web.config had an encrypted connection string, I was able to run the API just fine, and all database calls works appropriately)

The code below shows how I have circumvented the issue thus far. I have created a partial class for my context class, since the Peliquin.Context.cs class is generated code. I am decrypting the connection string, which as I've verified, looks exactly correct, then passing it into this class. The previous code was :base("name=ConnectionName")

The error message seems as if DbContext cannot have an actual connection string passed into it. But if I pass in the connection name, it runs into an issue with the connection string being encrypted.

I have searched and have been unable to find the solution to this seemingly simple problem. Any help would be appreciated.

ImgurImgurImgur

The web.config connection string, before I decrypt it at runtime: Imgur

Side note: This website will get deployed to several client sites, each that have their own database credentials. At the time of the installer installing the API and UI web applications onto the server, another application runs that updates the web.config file to the proper client database connection. This entire process is to have no user interaction. If anybody can think of a better method of changing the web.config connection string, then encrypting it, all without human interaction, please feel free to suggest an alternate solution to me.

Well, I seemingly fixed the problem myself. In the dynamically generated code Peliquin.Context.cs, I pass in the decrypted connection string, and it all works fine. What I don't like about this solution, is that the next time the edmx file is updated with the latest database changes, this file will dynamically be generated again, wiping out my changes, which will cause havoc in the future. Having another class take the constructor, still seems like a better solution.

public PeliquinDbContext(string connection):base(connection)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM