Why does my code-first ASP.NET MVC app suddenly not work just because I opened it from another location?

0

I have a code-first ASP.NET MVC app that ran smoothly and was able to access the data from SQL Server until I copied the project over to another location and opened it from there.

I get the following errors:

System.Data.DataException
HResult=0x80131501
Message=An exception occurred while initializing the database. See the InnerException for details.
Source=

StackTrace:

Inner Exception 1:
EntityException: The underlying provider failed on Open.

Inner Exception 2:
SqlException: Database 'C:\Users\BICHE\Desktop\FinalCSharpChallenge\FinalCSharpChallenge\App_Data\StudentContextDB.mdf' already exists. Choose a different database name.
Cannot attach the file 'C:\Users\BICHE\Desktop\MY REPOS3\The-Tech-Academy-C-Coding-Project\FinalCSharpChallenge\FinalCSharpChallenge\App_Data\StudentContextDB.mdf' as database 'StudentContextDB'.

My questions are: why does this happen just because I moved the project from my desktop to another location on my computer?

Can this be solved by making an "if" statement that proceeds to use the StudentContextDB if it exists, and creates it if it doesn't? (My instructor suggested this, so I'm thinking I will try this first)

Lastly, if this is the right solution, what would be the syntax for that particular statement? I've seen instructions for Drop and Create, but not Use or Create.

I appreciate any insight people may have on this issue!

sql-server
asp.net-mvc
code-first
asked on Stack Overflow Dec 31, 2018 by FreddieMercury • edited Jan 1, 2019 by marc_s

2 Answers

1

Short version here is that the db server still has a reference to the old location of the database. You moved it and tried to fire up the app and point to a new location of the database with the same name. The db server doesn't know how to handle that. It would be better to detach the database from the db server then move the files.

answered on Stack Overflow Dec 31, 2018 by John Babb
1

SqlException: Database '...' already exists. Choose a different database name.

It looks like your code is trying to recreate the database... If this is a new deployment, you probably want a new database ; you should modify your code to have a database location which is relative to your application home directory.

The other advantage is that, if you give your application to other people, they will have their database created on their computer under the relative path defined by you, so that will play softly as well.

answered on Stack Overflow Dec 31, 2018 by GMB

User contributions licensed under CC BY-SA 3.0