开发者

Can't recreate SQL Server Express database with Entity Framework Code First and MVC 3 without changing the database name

开发者 https://www.devze.com 2023-02-04 07:57 出处:网络
When I run the application with the following connection string the database file is created successfully.

When I run the application with the following connection string the database file is created successfully.

<add name="ConnString1"
     connectionString="Data Source=.\SQLEXPRESS;
                       Database=Database1;
                       Integrated Security=SSPI;
                       AttachDBFilename=|DataDirectory|as开发者_JS百科pnetdb.mdf;
                       User Instance=true"
     providerName="System.Data.SqlClient" />

If I delete the database file and try to run the application again the database file fails to be created and I get the following inner exceptions:

The underlying provider failed on Open.
{"Cannot open database \"Database1\" requested by the login. The login failed.\Database1\nLogin failed for user 'computer\\someuser'."}

If I change Database=Database1 to Database=Database2 in the connection string then the database file is created successfully. The problem repeats itself always.

How can I recreate the database file without having to change the database name?


Check to make sure the directory rights allow you to delete the mdf file and the the login has drop schema/table privileges directory rights are a common issue with mdf files due the high security placed on these files due to their potentially sensitive nature


I can see this is an older post - hopefully this can help someone in the same predicament.

Using code first, the first time the application runs it builds the db no problems - it knows it doesn't exist because it hasn't previously built it. Code first also takes a hash value of the models used and stores that in the new database - check for a table called EdmMetadata - thats where the hash value is stored. It uses the hash value to subsequently check if the model has changed from build to build, so it knows whether to drop the database and rebuild.

The second time through after you've deleted the database, it looks for the missing database to compare the model hash value, and can't find it because the database is now missing.

My workaround is to add a meaningless field (remembering to delete it after development) to one of the models to force the rebuild, without deleting the database. Alternatively, you could just modify the db hash value to force the rebuild.

This works with the code first application databases - not so sure with the membership database.

0

精彩评论

暂无评论...
验证码 换一张
取 消