I have an Entity Framework based MVC application linked to a SQL server.
This is not a production server, so, I am using Entity Framework Code First and taking advantage of Code First / Dropping the database when the schema changes.
I have the following connection string:
<add name="MyDbContext"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=appdb;User Id=xxx;Password=yyy;"
providerName="System.Data.SqlClient" />
I had various problems with EF/SQL, in the end, I created a new user with the sysadmin server role, I created the database appdb, set the new users default database to appdb and under User Mapping, I gave the user db_owner permissions (under user and default schema, it says dbo).
Anyway, everything worked as expected after I did this – The database was deleted/recreated with the needed tables.
However, I have now changed my classes. Using DropCreateDatabaseIfModelChanges causes a yellow screen with Unable to login to SQL Server with user:xxx error, and SQL server logging shows Login failed for user 'xxx'. Reason: Password did not match that for the login provided. [CLIENT: <local machine>]
If I launch the application on debug, it shows the following:
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.
If I change from DropCreateDatabaseIfModelChanges to DropCreateDatabaseAlways – everything works as expected…. I can then change back, and continue using the application without problems.
I really do not understand this and was wondering if anyone knows what is going on?
Try to add
Persist Security Info=Trueto your connection string.Edit:
Setting Persist security info to true allows database connection maintaining sensitive user information = password. I don’t know what magic EF does when dropping and recreating database but it most probably resets connection state and requires new authentication on opened connection. Without persisting security info opened connection cannot authenticate user again because it doesn’t know his password.
Btw. you can also try to download EFv4.1 Update 1 or better EFv4.2. I think it should fix this problem.