问题
So, I went to create an EDMX file today, and while going through the connection options the wizard asked if I wanted to "keep sensitive data out of the .config file and manually set it in code" this makes perfect sense to me (use my own encrypted "appsetting" for connection credentials).
Now, I'm sitting here trying to find out how to specify the credentials to my Entity Framework classes. The only thing I can find is the
db.Connection.ConnectionString
property, but I'm not really sure what to do with it all it contains is name=MyDatabaseName
.
TL;DR-- How does one create and use hard-coded connection for Entity Framework in C#? (I can un-hard code it once its in C#)
回答1:
If you cast the Connection object to an EntityConnection object, you can access the StoreConnection property which you can programmatically override with your hardcoded connectionstring.
See the example below:
EntityConnection entityConnection = (EntityConnection)context.Connection;
entityConnection.StoreConnection.ConnectionString = "YourConnectionString";
来源:https://stackoverflow.com/questions/6606020/set-credentials-for-entity-framework-in-code-without-using-integrated-security